I see in some sample code that autorelease is used. I am not familiar with the instances when this is required. For example, if I create an annotation object
Header file
@interface someViewController: UIViewController
{
Annotation *annotation;
}
@property (nonatomic, retain) Annotation *annotation;
@end
Implementation file
@implementation someViewController
@synthesize annotation
@end
Question: Is it the correct approach if I initialize my annotation object in the implementation file like this?
self.annotation = [[Annotation alloc] initWithCoordinate:location];
Do I need to set autorelease for this? Or can I just do it the normal way and add the release in the dealloc method?
this is correct:
self.annotation = [[[Annotation alloc] initWithCoordinate:location] autorelease];because annotation property is declared as a retain property, so assigning to it will increment its retain count.
you will also need, all the same, to release self.annotation in
-dealloc.in short:
init will set retain count to 1;
assigning to self.annotation, will set it to 2;
autorelease will set it back to 1 when the main loop is executed again;
release in dealloc will set the retain count to 0, so that the object will be deallocated);
the best way to think of
autoreleaseis the following, in my opinion:autoreleasewill “schedule” an “automatic”releasefor your object at some (near) point in future (typically when the control flow goes back to the main loop, but details are hidden in the hands of Apple).autoreleaseis mostly useful in conjunction withinit, specifically in the following cases:when you
inita local variable, so that you don’t have toreleaseit explicitly before it goes out of scope (the main loop will do that for you);when you return a pointer to an object you have just created without keeping ownership of it (typical case of the
create/make*kind of selectors, the receiver is required toretainit to get ownership);with properties that
retain, when you assign to them an object that they should own uniquely;with data structures that increment the retain count (
NSMutableArray,NSMutableDictionary, etc): you should generallyautoreleasea newlyinited object when you add it to such data structure.apart from case 2, it is evident that the use of
autoreleaseis meant to improve readability of the code and reduce the potential for errors (meaning that in all of the other cases, you could simplyreleaseexplicitly your object after the assignment or at the end of the scope).when using properties, you have always to check whether they are of the
retainorassign/copycase; in the first case, assigning a newlyinited object to a property generally requiresautorelease.Anyway, I would suggest at least skimming one of the many tutorial on memory management for iOS.