Why should a self-implemented getter retain and autorelease the returned object?

后端 未结 4 414
情话喂你
情话喂你 2020-12-28 08:52

Example:

- (NSString*) title {
    return [[title retain] autorelease];
}

The setter actually retained it already, right? and actually nobo

4条回答
  •  轮回少年
    2020-12-28 09:44

    It's not just for cases where someone releases the container, since in that case it's more obvious that they should retain the object themselves. Consider this code:

    NSString* newValue = @"new";
    NSString* oldValue = [foo someStringValue];
    [foo setSomeStringValue:newValue];
    // Go on to do something with oldValue
    

    This looks reasonable, but if neither the setter nor the getter uses autorelease the "Go on to do something" part will likely crash, because oldValue has now been deallocated (assuming nobody else had retained it). You usually want to use Technique 1 or Technique 2 from Apple's accessor method examples so code like the above will work as most people will expect.

提交回复
热议问题