自动释放然后保留给 setter
根据 Google Objective-C 风格指南 ,我们应该先自动释放,然后保留,如下所示:
- (void)setFoo:(GMFoo *)aFoo {
[foo_ autorelease]; // Won't dealloc if |foo_| == |aFoo|
foo_ = [aFoo retain];
}
在这种情况下,如果将 foo_ 设置为同一个实例,则不会被释放,从而形成更具防御性的 setter。
我的问题是,@property & 是这样的吗? @合成工作?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于自动释放而导致的释放直到当前运行循环结束时才会被调用,因此 foo_ 不会释放,因为首先调用保留,然后在当前运行循环结束时调用释放。但是,这不是 @synthesize 中生成的代码的工作方式。它的工作原理更像是,
当不需要更改时,此方法可以节省 cpu 周期,并消除使用自动释放池的少量开销。
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
This method saves cpu cycles when no change is necessary and takes out the small overhead of using the autorelease pool.