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

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

    Compare this code

      return [[title retain] release]; // releases immediately
    

    with this

      return [[title retain] autorelease]; // releases at end of current run loop (or if autorelease pool is drained earlier)
    

    The second one guarantees that a client will have a non-dealloced object to work with.

    This can be useful in a situation like this (client code):

     NSString *thing = [obj title];
     [obj setTitle:nil]; // here you could hit retainCount 0!
     NSLog(@"Length %d", [thing length]); // here thing might be dealloced already!
    

    The retain (and use of autorelease instead of release) in your title method prevents this code from blowing up. The autoreleased object will not have its release method called until AFTER the current call stack is done executing (end of the current run loop). This gives all client code in the call stack a chance to use this object without worrying about it getting dealloc'ed.

    The Important Thing To Remember: This ain't Java, Ruby or PHP. Just because you have a reference to an object in yer [sic] variable does NOT ensure that you won't get it dealloc'ed from under you. You have to retain it, but then you'd have to remember to release it. Autorelease lets you avoid this. You should always use autorelease unless you're dealing with properties or loops with many iterations (and probably not even then unless a problem occurs).

提交回复
热议问题