Apple is doing this in a setter method for an instance variable mainSprocket:
– (void)setMainSprocket:(Sprocket *)newSprocket {
[mainSprocket autorelease];
mainSprocket = [newSprocket retain];
return;
}
Why do they send -autorelease and not -release? Would a -release have a bad effect here? Actually it should not (for my understanding), because the -release just says that the current object held by the instance variable mainSprocket is no longer used by that instance variable. For the case that anyone else is still interested in exactly that object, that method could retain it, right? So -release should be fine, I think?
They’re doing
autoreleasehere in casenewSprocketandmainSprockethappen to be the same object. A call toreleasemight inadvertently deallocate the object before it can be retained on the next line, whereas theautoreleasewon’t be processed until the autorelease pool is drained at the end of the event loop.Consider this scenario:
The last line would cause an issue if
mainSprocketwasn’t autoreleased. Another convention you might sometimes see for setter code that does the same thing is:I’ll leave it up to others to comment on which is more appropriate or aesthetically pleasing 🙂