Autorelease 然后为 setter 保留 [英] Autorelease then retain for setters

查看:36
本文介绍了Autorelease 然后为 setter 保留的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 Google Objective-C 样式指南,我们应该自动释放然后保留:

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];
}

在这种情况下,如果 foo_ 被设置为同一个实例,则不会被释放,从而形成一个更具防御性的 setter.

In this case, foo_ will not be deallocated if being set to the same instance, making for a more defensive setter.

我的问题是,这是@property &@synthesize 工作吗?

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

推荐答案

release 由于 autorelease 直到当前 runloop 结束才会被调用,所以 foo_ 不会解除分配,因为首先调用 retain ,然后在最后调用 release当前运行循环.但是,这不是@synthesize 中生成的代码的工作方式.它更像

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;
   } 
}

此方法在不需要更改时节省了 cpu 周期,并消除了使用自动释放池的小开销.

This method saves cpu cycles when no change is necessary and takes out the small overhead of using the autorelease pool.

这篇关于Autorelease 然后为 setter 保留的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆