How can I fill an NSArray dynamically?

Thanks picture Thanks · May 8, 2009 · Viewed 41.8k times · Source

I have a for loop. Inside that loop I want to fill up an NSArray with some objects. But I don't see any method that would let me do that. I know in advance how many objects there are. I want to avoid an NSMutableArray, since some people told me that's a very big overhead and performance-brake compared to NSArray.

I've got something like this:

NSArray *returnArray = [[NSArray alloc] init];
for (imageName in imageArray) {
    UIImage *image = [UIImage imageNamed:imageName];
    //Now, here I'd like to add that image to the array...
}

I looked in the documentation for NSArray, but how do I specify how many elements are going to be in there? Or must I really use NSMutableArray for that?

Answer

Alnitak picture Alnitak · May 8, 2009

Yes, you need to use an NSMutableArray:

int count = [imageArray count];
NSMutableArray *returnArray = [[NSMutableArray alloc] initWithCapacity:count];
for (imageName in imageArray) {
    UIImage *image = [UIImage imageNamed:imageName];
    [returnArray addObject: image];
    ...
}

EDIT - declaration fixed