开发者

Resize NSArray programmatically

I have been trying to figure out if it is possible to programmatically resize an NSArray, using code similar to this:

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

Which would a new NSArray (Not a NSMutableArray if it is possible) that has the elments after the end of开发者_运维百科 oldarray padded with [NSNull null].


Since NSArray objects are immutable (cannot change the objects they contain) there's no use in adjusting the capacity of NSArrays.

You could however, write a category that did something along the lines of 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


While your question merits a "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


You want NSPointerArray.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜