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?
NSArray creates static arrays, and NSMutableArray creates dynamic arrays.
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...
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];
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 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With