Saturday, June 19, 2010

IBOutlet and Property in iPhone OS

iPhone OS provides a very nice structure and some templates or tools for creating views. For example, a UIViewController may contains several controls such as labels and text boxes. You can use XCode's templates to create xib file for views and .m class for code behind the view. Then use Interface Builder tool to layout the view in a visual designer environment.

The control variables in the view controller class are defined by IBOutlet key work as indicator so that in the Interface Builder you can link the visual controls to the field variables in the class. In many example codes, including Apple examples, I have seen that those class level variables are also linked to their corresponding properties. Variables can be private, protected or public, but property in Objective-C are public. In my projects, I have never have any usages to access or set those field variables through properties outside the class. Why the properties are defined? I have tried to not define properties, and my codes do working well. I am confused, what is the reason doing that?

I posted a question to SO. Soon I got an answer saying that this is a duplicated question. From the link to the duplicated question, I found the explanation from Apple's documentaion: Resource Programming Guide.

Actually, my question was not exactly a duplicated one, just similar topic. In my case, the field variable name is different from its related property name, because OS 2.0 allows it. This brings my question into a further interesting one. In short, in case of IBOutlet, property and xib loading, it is better to keep the variable name and property name the same. I tried several tests and I found some further in depth issues. Then I posted my finding and analysis as an answer to my SO question. I would not repeat the answer here again.