self.variable and variable difference [duplicate]

Solution 1:

It's important to note that dot-syntax is converted to a simple objc_msgSend call by the compiler: that is to say that underneath it acts exactly like a message send to the accessor for that variable. As such, all three of the following are equivalent:

self.myVariable = obj;

[self setMyVariable:obj];

objc_msgSend(self, @selector(setMyVariable:), obj);

Of course, this means that using dot-syntax actually results in a full message send, meaning calling a new function and all the overhead that is associated with it. In contrast, using simple assignment (myVariable = obj;) incurs none of this overhead, but of course it can only be used within the instance methods of the class in question.

Solution 2:

The @synthesize directive tells the compiler to generate accessors for your member variables, according to the specifications given in the @property directive in your .h file. (I.e., if you specify retain, the setter will retain the variable, and if you specify copy, it will copy it.)

The accessors will (unless you specify otherwise) be named propertyName and setPropertyName.

Using the . notation (note, not the self syntax as stated above) is saying that you want to use the accessors (a good thing if you are setting strings, and want to ensure the retain count is correct, for example).

So, within your class implementation:

  • self.bill = fred will call the accessor setBill.
  • bill = fred will set bill to fred directly, without going through the accessor.