views:

970

answers:

3

In other languages I could create a class then use this to create an array of objects in that class eg class price which is used in a performance class to define a price[] prices;

in objective C i cant get this to work, how do you do it?

The price class is an inherit of NSObject, can I use NSMutableArray?

+1  A: 

Yes, NSMutableArray is what you would want to use.

Eric Petroelje
+1  A: 

To answer your last question first: if you are storing instances of Objective-C object (which, as you say, inherit from NSObject) then yes, use NSMutableArray. However, this won't work for primitive types (like int, BOOL, char, char*, etc.).

Objective-C uses the C way of declaring arrays with one caveat: you can't allocate memory on the stack (which is what that does in C), only on the heap. That means you have to use malloc (prefer NSAllocateCollectable() on Leopard or later) and free to manage the memory. Also, you declare the array as a pointer to an array or pointers. Something like this: (Note: pulled from thin air, untested.)

Price **prices = malloc(numberOfEntries * sizeof(Price*));
...
free(prices);

Using an NSMutableArray is generally much easier than managing your own arrays. Just be aware of the memory management rules: collections call -retain on an object when it is inserted, and -release on it when it is removed (or on all objects if the collection is deallocated).

Quinn Taylor
+2  A: 

If you have a class Price, and it inherits from NSObject, then you can have an array of them stored in an NSArray or NSMutableArray. You could also store them in a C array, or an STL vector, although the memorymanagement sematics may be difficult in those cases.

In the case of an NSArray/NSMutableArray, the array takes an ownership reference on the object, so you can release it after adding it to the array, and it will remain in memory until it is removed from the array (and all other locations).

Code might look like:

NSMutableArray* a = [NSMutableArray array];
[a addObject:[Price price]];
// and/or
[a addObject:[[[Price alloc] init] autorelease];
// and/or
Price* p = [[Price alloc] init];
[a addObject:p];
[p release];
NSLog( @"The array is %@", a );
// Remember at this point you do not "own" a, retain it if you want to keep it, or use [NSMutableArray new] above

When a is released, all the Price objects it contains will be released (and potentially deallocated).

Peter N Lewis