Resize NSArray programmatically

I tried to figure out if it is possible to programmatically resize NSArray using code similar to this:

 NSArray *resize = [NSArray arrayResized:oldarray size:10]; 

What a new NSArray (not a NSMutableArray , if possible) that has elements after the end of the oldarray with [NSNull null] .

+4
source share
3 answers

Since NSArray objects are immutable (cannot modify the objects that they contain), there is no need to configure the capacity of NSArrays.

However, you could write a category that did something according to what you want:

 @interface NSArray (Resizing) -(NSArray *) resize:(NSInteger) newSize; @end @implementation NSArray (Resizing) -(NSArray *) resize:(NSInteger) newSize { int size = (newSize > [self count]) ? self.count : newSize; NSMutableArray *array = [NSMutableArray arrayWithCapacity:size]; for(int i = 0; i < size; i++) [array addObject:[self objectAtIndex:i]]; return [NSArray arrayWithArray:array]; } @end 
+2
source

While your question deserves β€œWhat are you really trying to do?”, Here is a possible solution:

 @interface NSArray (RCArrayAdditions) - (NSArray *)arrayByAppendingWithNulls:(NSUInteger)numberOfAppendedNulls; @end @implementation NSArray (RCArrayAdditions) - (NSArray *)arrayByAppendingWithNulls:(NSUInteger)numberOfAppendedNulls { NSMutableArray *expandedArray = [self mutableCopy]; for (NSUInteger i = 0; i < numberOfAppendedNulls; i ++) { [expandedArray addObject:[NSNull null]]; } return expandedArray; } @end 
+2
source

Do you want NSPointerArray .

0
source

All Articles