Search code examples
objective-cmemory-managementpropertiesretain

Memory management with properties


I'm starting to understand memory management better in objective-c, but there's something I don't understand. This is a property declaration:

@property (nonatomic, retain)UILabel *myLabel;

and this is its unseen synthesized setter (I think):

- (void)setMyLabel:(UILabel *)newValue {
    if(myLabel != newValue) {
        [myLabel release];
        myLabel = [newValue retain];
    }
}

Which saves you all the work of retaining and stuff every time, but say I set my property for the first time, its hasn't been allocated yet so its reference count is 0, right? So I do

UILabel *tempLabel = [[UILabel alloc] init];
self.myLabel = tempLabel;
[tempLabel release];

I'm not really sure what happens there, when it releases nothing , but say the property already has a value, and we set it. In the setter, first it gets released. So doesn't that make it dissapear? If its reference count is one, and then in the setter its released, how does it stay around to be set to the retained new value?

Thanks!!


Solution

  • I think you are confusing objects and references. A property is a reference to an object, not the object itself. When you set or unset a property it sends retains and releases to the objects it points to, but the reference itself is part of the object that the property is in (in this case self).

    It might be useful to read up on things like pointers and lvalues.