Arrays of NSObjects in Objective-C
-
30-09-2019 - |
Question
I've created an object, and now I'm trying to create an array full of these objects. I've tried a few different things with no success.
How can I do this?
Solution
You can do it one of two ways, with NSArray
or NSMutableArray
.
id obj1, obj2, obj3;
// This creates a static array
NSArray *array = [NSArray arrayWithObjects: obj1, obj2, obj3, nil];
// This creates a dynamic array
NSMutableArray *mutarray = [NSMutableArray array];
[mutarray addObject:obj1];
[mutarray addObject:obj2];
[mutarray addObject:obj3];
OTHER TIPS
NSMutableArray * arrayOfFoos = [NSMutableArray array];
for (int i = 0; i < 100; ++i) {
Foo * f = [[Foo alloc] init];
[arrayOfFoos addObject:f];
[f release];
}
You can use an NSArray
, take a look at Apple's documentation.
If you wanna add them incrementally consider using a mutable collection like an NSMutableArray
(here in the doc)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow