views:

48

answers:

3

If you declare a property with a retain attribute, do you need to release the property before you set it to nil?

What does the @synthesize directive do?

A: 
  1. No, in fact you don't need to release it at all. That would be a bug. You don't even have to set it to nil, unless you really want to control when it's released (before your own class' release, that is).
  2. Creates the getter and setter methods for you, presumably in an optimized way.

For more information I suggest you read the relevant page in the guide.

Aviad Ben Dov
+2  A: 

You do not need to release a retained property before setting it to nil as long as you use a setter that does the release for you. If you've declared a property with retain, the synthesized setter will do the release for you. And that brings us to the @synthesize directive. It simply tells the compiler to write the setters and getters for you using the attributes you've specified in @property.

James Huddleston
+2  A: 

You do need to release the (retained) object before setting another object or nil in your property var but this is done by the accessor, if you like this.

self.myVar = nil;

What @synthesize does is to create accessor methods automatically for you (In case you don't define them)

so, if you wrote your property as:

@property (nonatomic, retain) NSObject *property;

then you can think that synthesized accessors will be something equivalent(I said equivalent because we don't certainly know how this is done... for more info read doc below) to the following:

- (void) setProperty:(NSObject *)aProperty{
    if(property != aProperty){
        [property release];
        property = [aProperty retain];
    }
}

- (NSObject*) property{
    return property;
}

This part is SUPER important and I would suggest to spend as most time available to learn about this. (Also read copy and assign)

Apple doc on Properties

nacho4d