保留/自动释放已保留的财产有什么额外好处?

发布于 2024-11-01 05:50:38 字数 332 浏览 1 评论 0原文

在我目前正在进行的一个项目中,我正在研究前辈的代码。我在这里遇到的一件事是,有这样的吸气剂:

- (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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

眼眸 2024-11-08 05:50:38

想象一下:

id x = [[A alloc] init];
NSDictionary *userInfo = [x userInfo];
[x release];
// Do something with userInfo ...
// Would fail if the getter did not retain/autorelease.

如果 getter 没有执行保留/自动释放操作,则会失败,因为当 x 被释放时,userInfo 也会被释放。

Imagine this:

id x = [[A alloc] init];
NSDictionary *userInfo = [x userInfo];
[x release];
// Do something with userInfo ...
// Would fail if the getter did not retain/autorelease.

This would fail if the getter did not do the retain/autorelease thing because userInfo would get deallocated when x gets deallocated.

单调的奢华 2024-11-08 05:50:38

它允许返回的结果在整个当前调用堆栈中持续存在,即使拥有的对象在此期间被释放也是如此。 Cocoa 中的惯例是,任何由没有所属引用的 getter 返回的东西(即名称中没有“new”、“alloc”、“retain”或“create”的任何 getter)将持续至少封闭的自动释放池。

例如:

Object1 *object1 = [[Object1 alloc] init];
ResultObject *result = [object1 someResult];
[object1 release];

// result is still valid here, even though object1 was released

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:

Object1 *object1 = [[Object1 alloc] init];
ResultObject *result = [object1 someResult];
[object1 release];

// result is still valid here, even though object1 was released
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文