Quote:
Originally Posted by Max
this tutorial is great, but I'm still a bit confused about autorelease stuff:
In this example:
Code:
-(void)doSomething
{
SomeObject *obj = [[[SomeObject alloc] init] autorelease];
self.obj = obj;
}
When does autorelease get called on *obj value? After doSomething method ends or in the current class dealloc?
Then again, in this code:
Code:
-(void) logValue:(int)intValue
{
NSLog(@"%@", [NSString stringWithFormat:@"%d", intValue]);
}
When does stringWithFormat value get destroyed? After logValue ends or somewhere after current class dealloc?
|
Basically, "autorelease" causes the object to be added to a system-managed list of objects that need to be released. The actual release typically happens after the current message is processed. Conceptually, the message handler does:
1) Set up the autorelease pool
2) Call the message handler
3) Delete any objects that got put into the autorelease pool during message processing.
Thus, an object on which autorelease has been called will be "alive" for the rest of the current message handler, but won't survive past that unless it's retained somewhere.
In your first example, the "self.obj = obj" call (assuming that the property is set up to "retain") will cause a "retain" call on the object. Thus, the "use count" on that object will be 2 - one from your original alloc/init, and one from the retain. At the end of the message processing, since you called autorelease on "obj," the autorelease pool will call "release" on "obj", which will decrement the use count to 1. The object will not be dealloc'd, because it's use count is non-zero - your class is still holding onto it. Later on, when that object is replaced or the holding object is destroyed, a second release call will be made on "obj", which will decrement the use count to zero and cause it to be dealloc'd.
"stringWithFormat" is a great example of where autorelease is useful. The rule "if you alloc it, you need to release it" works great for objects that you create, but what about factory methods? In this case, "stringWithFormat" creates a string and calls autorelease on it before returning it to you. Thus, unless you retain the string, it will get released at the end of the current message handler. Using this paradigm means that if you get an object from anything other than an alloc/init method, you don't have to worry about whether or not to release it. If the factory method means the object to be ephemeral, it will have called autorelease on it for you. If not, then the factory has probably retained it, and will be responsible for releasing it at the appropriate time. Essentially, the normal "lifecycle" of that object is determined by the factory. (Although, of course, you can extend the life of such an ephemeral object by retaining it yourself and releasing it later.)
Hope that helps....