Question

I have a simple question. Does autorelease work when the retain count is high?

for example... If I am in a view controller and do the following:

[self retain];
[self retain];
[self retain];
[self retain];
[self autorelease];

If I pop the view, will it be released?

Thanks.

Was it helpful?

Solution

Autorelease simply adds the object to an autorelease pool. When the autorelease pool is deallocated a release message is sent to the object, and all the other objects in that pool. If your retain count is still greater than zero and you do no further releases, then you will have a memory leak.

I believe that if you do as you say above you will have a retain count of 5 (one from the alloc, and the 4 from the four retains you have above). You added the object to the autorelease queue so later it will receive a release and reduce the retain count by one. Finally popping the view should reduce it by one more. That would leave a retain count of 3. So I would think that you would have a memory leak.

However if you are using iOS 5, the latest compiler uses ARC (automatic reference counting) and you don't need to worry about this problem. Well for the most part.

EDITED: Corrected when objects are sent a release from the autorelease pool. See: Advanced Memory Management Sorry for the wrong information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top