What's the added benefit of retain/autoreleasing an already retained property?
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:
- (NSDict开发者_如何学JAVAionary *)userInfo
{
return userInfo;
}
Cheers,
EP.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.
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
精彩评论