问题
According to the Google Objective-C Style Guide, we should autorelease then retain as so:
- (void)setFoo:(GMFoo *)aFoo {
[foo_ autorelease]; // Won't dealloc if |foo_| == |aFoo|
foo_ = [aFoo retain];
}
In this case, foo_ will not be deallocated if being set to the same instance, making for a more defensive setter.
My question is, is this how @property & @synthesize work?
回答1:
release due to an autorelease isn't called until the end of the current runloop so foo_ wont dealloc because retain is called first followed by release at the end of the current runloop. However, this isn't how the code generated in @synthesize works. It works more like
- (void)setFoo:(GMFoo *)aFoo {
if (aFoo != foo_) {
[aFoo retain];
[foo_ release];
foo_ = aFoo;
}
}
This method saves cpu cycles when no change is necessary and takes out the small overhead of using the autorelease pool.
来源:https://stackoverflow.com/questions/4767939/autorelease-then-retain-for-setters