Reason to use ivars vs properties in objective c

You can think of the syntax for synthesizing properties as @synthesize propertyName = variableName.

This means that if you write @synthesize highscore = _highscore; a new ivar with the name _highscore will be created for you. So if you wanted to you could access the variable that the property is stored in directly by going to the _highscore variable.

Some background

Prior to some version of the compiler that I don’t remember the synthesis statement didn’t create the ivar. Instead it only said what variable it should use so you had to declare both the variable and the property. If you synthesized with a underscore prefix then your variable needed to have the same prefix. Now you don’t have to create the variable yourself anymore, instead a variable with the variableName that you specified in the synthesis statement will be created (if you didn’t already declare it yourself in which case it is just used as the backing variable of the property).

What your code is doing

You are explicitly creating one ivar called highscore when declaring the variable and then implicitly creating another ivar called _highscore when synthesizing the property. These are not the same variable so changing one of them changes nothing about the other.

Should you use variables or not?

This is really a question about preference.

Pro variables

Some people feel that the code becomes cleaner if you don’t have to write self. all over the place. People also say that it is faster since it doesn’t require a method call (though it is probably never ever going to have a measurable effect on your apps performance).

Pro properties

Changing the value of the property will call all the necessary KVO methods so that other classes can get notified when the value changes. By default access to properties is also atomic (cannot be accessed from more then one thread) so the property is safer to read and write to from multiple thread (this doesn’t mean that the object that the property points to is thread safe, if it’s an mutable array then multiple thread can still break things really bad, it will only prevent two threads from setting the property to different things).

Leave a Comment