开发者

Autorelease then retain for setters

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 开发者_如何学Cif being set to the same instance, making for a more defensive setter.

My question is, is this how @property & @synthesize work?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜