Create an unknown number of objects
I need to create a specific number instances of an object based on a variable. so the pseudo code looks kinda like this
for(int x; x < aInt; x++) {开发者_Python百科
//create object and initialize it
}
how would I do that and create a different object each time with a different name and memory location?
Stick the reference in a NSMutableArray
(or a NSArray
, given that you appear to know the size in advance).
NSMutableArray *array = [[NSMutableArray alloc]init]
for(int x; x < aInt; x++) {
//create object and initialize it
YourObject *o = [[YourObject alloc]init];
[array addObject:o];
[o release];
}
// do whatever you need to do with the objects
A NSDictionary
/NSMutableDictionary
is certainly an option as well, depending on what your requirements are.
Just use a NSMutableArray
:
NSMutableArray *objectsArray = [NSMutableArray arrayWithCapacity:(YourIntegerValue)];
for(int x; x < aInt; x++) {
//create object and initialize it
[objectsArray addObject:(YourObject)];
}
Don't forget to release the array after you're done working with it!
精彩评论