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 autorelease
is the following, in my opinion: autorelease
will "schedule" an "automatic" release
for 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).
autorelease
is mostly useful in conjunction with init
, specifically in the following cases:
when you init
a local variable, so that you don't have to release
it 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 to retain
it 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 generally autorelease
a newly init
ed object when you add it to such data structure.
apart from case 2, it is evident that the use of autorelease
is meant to improve readability of the code and reduce the potential for errors (meaning that in all of the other cases, you could simply release
explicitly 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 retain
or assign
/copy
case; in the first case, assigning a newly init
ed object to a property generally requires autorelease
.
Anyway, I would suggest at least skimming one of the many tutorial on memory management for iOS.