sábado, 3 de abril de 2010

@properties in objective-c

When you declare an @property in Objetive-C, what is happening is that you are generating three things, a getter method, a setter method and the hability to use object.property in your code.
When you do:

@property (assign) int myProperty

What is happening is that you have to implement 2 methods:

-(int)myProperty;
-(void)setMyProperty;

and then when you do:

object.myProperty = 2;

what is happening is:

[objecti setMyProperty:2];

And if you write:

int a = object.myProperty;

the executed code is actually:

int a = [object myProperty];

So in order to have a @property you don´t even need to have that property as an instance variable for your class.

It is very common to declare a @property with the same name and type of an instance variable and then @synthesize it, so the compiler generates the getter and setter method.

The problem begins when you do a @property from another object, not the basic types:

@property (nonatomic,retain) NSString* myStringProperty;

Here it will generate the 2 methods described above, but the setter will retain the object. That means you shouldn´t do:

object.myStringProperty = [[NSString alloc] initWithFormat:@"this will leak!"];

Because the [NSString alloc] will give you an object with a retain count 1, and the [object setMyStringProperty:] will retain it giving it a retain count of 2, so when you call [myStringProperty release] in your code it will decrease the retain count back to one(assuming it wasn´t retained in other places) and it will not be deallocated. probably at this time you will lose the references to the string object and you will never see that memory again.