Ever since the modern runtime was introduced with Obj-C 2.0, Mac and iOS developers have been able to use implicit instance variables with property declarations. Instead of listing all the instance variables that back your properties in the class header or in a private category in the implementation file, you simply synthesize your property and the runtime generates the iVar for you.

While useful, the improvement was poorly implemented. The runtime automatically generated iVars whose name directly corresponded to the property name. This made it easy to introduce bugs into your code when you directly accessed the iVar without going through the getter and setter. Problems also arose when you dynamically implemented a setter or anywhere else a method took an argument name that matched the property name, a common enough occurrence when you’re adding delegate and datasource methods to a controller class. The accepted solution has been to synthesize your properties to iVars with an underscore either prefixing or suffixing the name.

With the release of Xcode 4.4 and LLVM 2.0 just a few weeks ago, developers welcomed a number of further improvements to Obj-C. In addition to the new object literals, developers can also take advantage of auto synthesis. It is now no longer necessary to synthesize your properties. Simply declare a property in the header file or in the private category and everything else is handled for you. At compile time LLVM generates your mutator methods and at runtime Obj-C generates the backing instance variable. Most excellent.

The latest update included a hidden gem: it also solved the iVar naming problem. Instance variables are now created with an underscore prefacing the property name. So that now, when you declare a cities property, you get a _cities instance variable automagically created for you, which should prevent you from introducing those previously mentioned bugs. Of course you can still synthesize the property yourself to whatever iVar you want if the circumstances warrant it.

A couple of screenshots to accompany the post, showing the moment of discovery. I declared a cities NSArray property and was screwing around with some example code. Remember, don’t access those instance variables directly! Use your mutators! Go through self! The images are for demonstration purposes only. =)

 

Leave a Reply