How can I fill an NSArray dynamically?

41,905

Solution 1

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

Solution 2

You'll need to use an NSMutableArray for that because adding is mutation and NSArray is immutable.

You could make a populated NSMutableArray into an NSArray afterwards (see here for a discussion) but you won't be adding items to a regular old NSArray anytime soon.

Solution 3

Would this be a good time to use an NSMutableArray?

I know you mentioned that you would like to avoid it, but sometimes there's a reason for things like this.

Solution 4

I would advise optimising only when you know NSMutableArray is causing you a performance hit but if it is, you can always create a static aray from a mutable array after you have populated it. It depends on if the performance hit is caused by you subsequent use of the NSMutableArray or just by creating it.

My guess is that this isn't going to be the performance bottleneck on your app.

Share:
41,905
Thanks
Author by

Thanks

I like to play guitar. Sometimes I need to develop software. But I hate it ;) I mean... it sucks. It really does. Well, not always. Oh, and I think I'm the guy with the most questions here.

Updated on September 21, 2020

Comments

  • Thanks
    Thanks over 3 years

    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?