How can I fill an NSArray dynamically?
-
22-07-2019 - |
Question
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?
Solution
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
OTHER TIPS
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.
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.
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.