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

后端 未结 4 383
情话喂你
情话喂你 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:47

    I haven't seen this pattern before, but it seems fairly pointless to me. I guess the intent is to keep the returned value safe if the client code calls "release" on the parent object. It doesn't really hurt anything, but I doubt that situation comes up all that often in well-designed libraries.


    Ah, ok. from the documentation smorgan linked to, it seems this is now one of the methods that Apple is currently recommending that people use. I think I still prefer the old-school version:

    - (NSString *) value
    {
        return myValue;
    }
    
    - (void) setValue: (NSString *) newValue
    {
        if (newValue != myValue)
        {
           [myValue autorelease]; // actually, I nearly always use 'release' here
           myValue = [newValue retain];
        }
    }
    

提交回复
热议问题