Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fill an NSArray dynamically?

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?

like image 590
Thanks Avatar asked May 08 '09 12:05

Thanks


People also ask

What is difference between NSArray and NSMutableArray?

NSArray creates static arrays, and NSMutableArray creates dynamic arrays.

Is NSArray ordered?

The answer is yes, the order of the elements of an array will be maintained - because an array is an ordered collection of items, just like a string is an ordered sequence of characters...

How do you declare NSArray in Objective C?

Creating an Array ObjectThe NSArray class contains a class method named arrayWithObjects that can be called upon to create a new array object and initialize it with elements. For example: NSArray *myColors; myColors = [NSArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];

What is NSMutableArray?

The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray .


1 Answers

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

like image 107
Alnitak Avatar answered Sep 30 '22 20:09

Alnitak