Suppose you have several Class object declarations and add it into a NSMutableArray, then you modify both the Class objects and the NSMutableArray object. What happens?
Code Example:
MyClass *item1;
MyClass *item2;
NSMutableArray *itemHolder;
item1 = [[MyClass alloc] init];
item2 = [[MyClass alloc] init];
itemHolder = [[NSMutableArray alloc] initWithObjects:item1,item2,nil];
-(void)someFunction{
[item1 setVarName:@"item1"];
[item2 setVarName:@"item2"];
for(MyClass *items in itemHolder) [items setVarName:@"item"];
}
I think I usually release item1 and item2 after adding it into itemHolder but it does not break memory management rules right? Because at the end in dealloc, you can still release everything
-(void)dealloc{
[item1 release];
[item2 release];
[itemHolder release];
}
When you add the objects (item1 and item2) to the array, the array is just storing the pointer. The object itself is not copied.
So when you setVarName on item1 or setVarName on the first item in the NSArray, both actions are affecting exactly the same object (the same instance)
As for memory mgmt, when you add the items to the NSArray, the NSArray (mutable or not) will retain each of them. When the array is deallocated, it will release each of them.
If you have some other need to retain each item individually, then you should do so (like in your example). But keep in mind in normal programs, you’re more often going to just add new objects to the array and release them immediately since the array has retained them.
But again, it’s hard to generalize without looking at a specific example.