What happens when you add a Class into NSMutableArray and you change both that object and the array?
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开发者_如何学Go) [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.
If you try to release something that has already been released then you will probably get EXC_BAD_ACCESS or a segmentation fault. Try to make sure that you don't release the same object twice.
If you release the object contained in the array and later release item1 or item2, you will be releasing the same object twice from two different references
If you change the class object then the version in the array will be affected as well, and vice versa.
精彩评论