Sunday, December 14, 2008

More on Outlets - Instance Variables vs. Properties

Last week, I wrote about the difference between using the IBOutlet keyword in front of your instance variable declaration, versus putting it in the property declaration. After a little investigation, I came to the conclusion that there was no difference, and it was purely stylistic.

One reader sent me some information that showed me I was wrong about it being purely stylistic. There is at least one scenario where it matters very much where you put the keyword, and that's if you use a different name for your underlying variable than for the property. So, if you define a variable
UIView *_myView;
And you then define a property
@property (nonatomic, retain) UIView *myView;
And synthesize the property to use that variable
@synthesize myView=_myView;
Then, in this case, it very much matters where you put the keyword. If you put the IBOutlet keyword in front of the instance variable, Interface Builder will not realize that there is an accessor and mutator for this variable - it will look for a mutator called set_myView: and completely miss the fact that there is a mutator called setMyView:. Therefore, the mutator will not get used and the outlet will not get retained.

It doesn't seem to hurt anything if Interface Builder goes directly to the instance variable - this was the way things worked in the days before properties, but you should be aware of the fact that it's not using your mutator to connect the outlet. As a result, if you do not use the same name for your properties and underlying instance variables for your outlets, I strongly recommend that you put your IBOutlet keyword in the property declaration.

Thanks, Kevin, for bringing this to my attention!

No comments: