This is a bit of a silly question, but if I want to add an object to an array I can do it with both NSMutableArray
and NSArray
, which should I use?
When deciding which is best to use:
NSMutableArray
is primarily used for when you are building collections and you want to modify them. Think of it as dynamic.
NSArray
is used for read only inform and either:
What you are actually doing here:
NSArray * array2;
array2 = [array2 arrayByAddingObject:obj];
is you are creating a new NSArray
and changing the pointer to the location of the new array you created.
You are leaking memory this way, because it is not cleaning up the old Array before you add a new object.
if you still want to do this you will need to clean up like the following:
NSArray *oldArray;
NSArray *newArray;
newArray = [oldArray arrayByAddingObject:obj];
[oldArray release];
But the best practice is to do the following:
NSMutableArray *mutableArray;
// Initialisation etc
[mutableArray addObject:obj];