if i release NSMutableArray is released, what happens to the objects in the array if their retainCount is greater then 1?
if i have a NSMutableArray with a retain count of 1 and this array has multiple class A objects that have variables with retain count greater then 1, what happens to 开发者_开发问答this variables if i release the array? are they forced to release every retained count and release space or wil they stil occupy memory ?
Releasing the array has the same effect as removing all the items from the array. That is, the array no longer claims ownership of them. If anyone else has retained the objects, they'll continue to exist. If not, they'll be deallocated.
This is just the normal set of memory rules in effect. If you retain an object, you must release it. Conversely, other bits of code (like an array) are allowed to retain and release that object when they want to own it, too, but if everyone follows the rules, nobody gets surprised.
Think of the retain
call as a +1 and the release
call as -1. Your call to release the NSArray
releases the NSArray
, and then that in turn will send a release
to each item it held, but because the NSArray
took a retain
on them when you added them it is just balancing its retain
/release
calls.
It is often best to concentrate more on balancing your retain
and release
calls than it is to imagine what the retain count will be at any particular time.
Your array will be deallocated when you send that release since the retainCount==0. When your program deallocates a collection type object (like an array), it will perform a release on all the objects in the collection. All a release does is decrement the retain count. Deallocation does not occur until retainCount==0. So if the objects in your array have a retainCount==2, then after the array is deallocated they will have a retainCount==1. If no other variables reference any of these objects, then they will continue to exist as memory leaks.
Strictly speaking, when retainCount
is 1 and you release the array, the array will be "deallocated". And right before the array is deallocated, the array will send release
message to each element in the array. I think you can imagine the rest.
精彩评论