Autorelease then retain for setters

别等时光非礼了梦想. 提交于 2019-12-11 00:27:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!