Acceptable ways to release a property

后端 未结 4 524
滥情空心
滥情空心 2020-12-19 12:31

Assume there is a class with the following interface:

#import 

@interface MyClass :          


        
4条回答
  •  既然无缘
    2020-12-19 12:51

    the pattern of release and renew is merely a semantic. You get a retain count for each of the following.

    myObject = [Object alloc]
    objectCopy = [myObject copy]
    myNewObject = [Object newObjectWithSomeProperties:@"Properties"] // Keyword here being new
    // And of course
    [myObject retain]
    

    a property with the modifier (retain) or (copy) will have retain count on it. the backing store _myDate is merely where the object is actually stored.

    when you get a retain count you need to release. Either immediately with the [myObject release] message or let the pool release it with [myObject autorelease]

    Whatever the case, Any retain you are given (implicit or explicit) will need to be released. Otherewise the garbage collector will not collect your object and you will have a memory leak.

    the most common usage in

    Object myObject = [[[Object alloc] init] autorelease]; // Use this when you dont plan to keep the object.
    
    Object myObject = [[Object alloc] init];
    self.myProperty = [myObject autorelease]; // Exactally the same as the Previous. With autorelease
                                             // Defined on the assignment line.
    
    self.myProperty = [[[Object alloc] init] autorelease]; // Same as the last two. On one line.
    

    I will demonstrate other possibilities

    // Uncommon. Not incorrect. But Bad practice
    myObject = [[Object alloc] init];
    self.myProperty = myObject;
    
    // Options
    [_myProperty release] // Bad practice to release the instance variable
    [self.myProperty release] // Better practice to Release the Property;
    
    // releasing the property or the instance variable may not work either.
    // If your property is using the (copy) modifier. The property is copied rather then retained.
    // You are still given a retain count.
    // But calling release on a copy will not release the original
    
    [myObject release]; // Best Practice. Good when Threading may run the autorelease pool
    [myObject autorelease]; // As good as the previous. 
                            // But may leave your object in memory during long operations
    

    Essentially, your object given a retain will be the same object in the Property the Variable and the Instance Variable. Releasing on any of them will release it. However. Best practice says that if you retain an object. Best to call release on the same variable of that object. Even if Autorelease and retain is called on the other side.

    // Other items that give you a retain count. Core Media or Core Anything Functions that have Create Or Copy in the name.

提交回复
热议问题