Flaky Goodness

My Problem with Objective-C Dot Syntax

March 3, 2014

Say you have a class Employee with the property CGFloat salary. Here are two choices to set this property from inside an instance of the class.

_salary = 35000.00;


[self setSalary:35000.00];

These do very different things. In the first case you directly set the instance variable (ivar) and do not trigger any observers or other hooks that may be watching salary for changes.

The second is actually calling the method setSalary, whether defined explicitly in your code or generated for you by the compiler. It is also triggering anything in the framework that may be set up to detect changes to the property.

In general, you would always want to use the second form rather than the first. Something out there might be expecting to be notified when salary changes, and if you set it directly you are doing an end-run around one of the things that makes programming in Objective-C so nice. Sometimes though, you actually do want to use direct ivar assignment.

Now, consider a third way of setting the salary.

self.salary = 35000.00;

Is this like the first form (direct ivar assignment) or like the second (property assignment)?