what happens if you add your just created object to a mutable array, and you release your object [duplicate]
Possible Duplicate:
what happens if you add your just created object to a mutable array, 开发者_C百科and you release your object in objc
what happens if you add your just created object to a mutable array, and you release your object
NSArray or NSMutableArray retains the objects. So your object will be retained until you remove the object from the array or release the array itself.
MyClass *obj = [[MyClass alloc] init];
[myMutableArray addObject:obj]; // obj is retained by array
[obj release]; // release to match the previous alloc
[myMutableArray removeObject:obj]; // obj receives a release message
[myMutableArray release]; // all objects in array receives release message if it is not owned anywhere else
Assuming it was an object you owned (e.g. it was created with alloc
instead of some convenience constructor like stringWithFormat:
), the array is now the sole owner of the object. When the array is deallocated or the object is removed from the array, it will be deallocated unless another object has taken ownership of it.
If you have something like this:
MyObject *obj = [[MyObject alloc] init];
[myArray addObject:obj];
[obj release];
You can say that myArray
becomes the owner of obj
. When adding an object to an array or dictionary, it gets retained by that array or dictionary. Since you release it (give up ownership), the array or dictionary has the only retaining reference and thus becomes the owner. In this example, obj
gets deallocated as soon as myArray
gets deallocated (given that nobody else queried it from the array and retained it).
精彩评论