Home / iPhone Tips and Tutorials

Hiding Instance Variables

When properties were first developed, they were looked at as a way to avoid the tedium of writing accessors for instance variable based properties.

People used to think about properties as a way to access instance variables. In fact, instance variables should not be equated to properties, and more important, instance variables should not be made public. (Doing so violates the object-oriented principle of encapsulation, but that's a conversation for a different time). In fact, Apple's new approach is to put instance variable declarations in the implementation file of the class.

Before the new Objective-C compiler that comes with Xcode 4.2 came about, programmers declared instance variables in the header file in the @interface class declaration. In the old times, you would have added the following bolded code to the RTViewController.h file:

@interface RTViewController : UIViewController
		<DestinationControllerDelegate> {
  AVAudioPlayer *backgroundAudioPlayer;
  SystemSoundID burnRubberSoundID;
  BOOL touchInCar;
}

This approach made instance variables (ivars) visible to everyone and every thing and was, as I mentioned, at odds with the principle of encapsulation (even if the variables couldn't be accessed).

In Xcode 4.2, you can hide instance variables by declaring them in the implementation file in one of two ways. The first is as a class extension, which you create by adding a second interface block in the implementation file followed by open and close parenthesis:

@interface RTViewController () {

  AVAudioPlayer *backgroundAudioPlayer;
  SystemSoundID burnRubberSoundID;
  BOOL touchInCar;
}
@end

The second way is by declaring the instance variable in the @implementation block of the class:

@implementation RTViewController

AVAudioPlayer *backgroundAudioPlayer;
SystemSoundID burnRubberSoundID;
BOOL touchInCar;
Tip
You can also use class extensions to have a publicly declared set of methods and to then have additional methods declared privately for use solely by the class:
@interface RTViewController () {

  AVAudioPlayer *backgroundAudioPlayer;
  SystemSoundID burnRubberSoundID;
  BOOL touchInCar;
}
- (void) privateMethod;
@end
[Previous] [Contents]