保留/自动释放已保留的财产有什么额外好处?
在我目前正在进行的一个项目中,我正在研究前辈的代码。我在这里遇到的一件事是,有这样的吸气剂:
- (NSDictionary *)userInfo
{
return [[userInfo retain] autorelease];
}
显然 userInfo 已经被类保留,我没有得到的是:retain-autoreleasing 这个对象的附加值是什么?这种方法有什么不同:
- (NSDictionary *)userInfo
{
return userInfo;
}
干杯,
EP。
At a project I'm currently working on I'm working through code of my predecessors. One of the things I encounter here and there are getters like this:
- (NSDictionary *)userInfo
{
return [[userInfo retain] autorelease];
}
Obviously userInfo is already retained by the class, what I don't get is: What's the added value of retain-autoreleasing this object? What would be the difference with this method:
- (NSDictionary *)userInfo
{
return userInfo;
}
Cheers,
EP.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
想象一下:
如果 getter 没有执行保留/自动释放操作,则会失败,因为当
x
被释放时,userInfo
也会被释放。Imagine this:
This would fail if the getter did not do the retain/autorelease thing because
userInfo
would get deallocated whenx
gets deallocated.它允许返回的结果在整个当前调用堆栈中持续存在,即使拥有的对象在此期间被释放也是如此。 Cocoa 中的惯例是,任何由没有所属引用的 getter 返回的东西(即名称中没有“new”、“alloc”、“retain”或“create”的任何 getter)将持续至少封闭的自动释放池。
例如:
It allows the result returned to persist for the entirety of the current call stack even if the owning object is deallocated in the interim. The custom in Cocoa is that anything that is returned by a getter without an owning reference (ie, any getter without 'new', 'alloc', 'retain' or 'create' in the name) will last for at least as long as the enclosing autorelease pool.
For example: