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

时间:2011-04-15 16:04:32

标签: objective-c memory-management retain autorelease

在我正在进行的项目中,我正在研究前任的代码。我遇到的其中一件事就是这样的吸气鬼:

- (NSDictionary *)userInfo
{
    return [[userInfo retain] autorelease]; 
}

显然userInfo已经被类保留了,我得不到的是:retain-autoreleasing这个对象的附加值是什么?这种方法有什么不同:

- (NSDictionary *)userInfo
{
    return userInfo;
}

干杯,
EP。

2 个答案:

答案 0 :(得分:3)

它允许返回的结果在整个当前调用堆栈中保持不变,即使在临时中取消分配拥有对象也是如此。 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

答案 1 :(得分:3)

想象一下:

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没有执行retain / autorelease事件,这将失败,因为userInfox被取消分配时将被释放。

相关问题