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.

Um comentário:

  1. "Loucura, loucura, loucura", diria o artista que preenche de vazio os sábados na TV!!!
    Vim visitar seu blog por causa do comentário no blog do Nicholas Gimenes, maaaas... risos!
    Eis os pensamentos que borbadearam minha cabecinha assim que cheguei:
    1)Hááá! Tem que ser tudo em inglês?! Num podia ser em espanhol, não?! Inglês dá tanto trabalho!...
    2)Noossa! Ou seu blog é sobre assuntos técnicos ou, realmente, meu inglês está pior do que minhas habilidades matemáticas! (E isso seria algo grandioso, vale esclarecer!)
    3)Seria legal um post que expusesse mais do humor simples, direto e sarcástico - humor inteligente - que pude sentir no pequeno comentário no blog do Nicholas e no título do seu próprio blog. :) Sugestãozinha de uma visitante "inxirida" (não sei se este termo é só aqui do Nordeste...)! Risos.
    Abraço grande.

    ResponderExcluir