How to Hide Instance Variables in Your iOS App - dummies

How to Hide Instance Variables in Your iOS App

By Jesse Feiler

When properties were first developed for iOS app programming, 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 shouldn’t be equated to properties, and more important, instance variables shouldn’t 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.

Xcode 4.2 came about,programmers declared instance variables in the header file in the @interface class declaration. In the old times, you would’ve added the following bolded code to the TestDriveController.h file:

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

This approach made instance variables (ivars) visible to everyone and everything and was at odds with the principle of encapsulation (even if the variables couldn’t be accessed).

Starting with Xcode 4.2, you can now 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 section in the implementation file followed by open and close parentheses:

@interface TestDriveController () {
 AVAudioPlayer *backgroundAudioPlayer;
 SystemSoundID burnRubberSoundID;
 BOOL touchInCar;
}
–d

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

@implementation TestDriveController
AVAudioPlayer *backgroundAudioPlayer;
SystemSoundID burnRubberSoundID;
BOOL touchInCar;

A class extension is a variation of an Objective-C category.

The approach you use is your choice; using class extension makes the variables easier to distinguish.

You can also use class extensions to have a publicly declared set of methods and then declare additional methods for use solely by the class:

@interface TestDriveController () {
 AVAudioPlayer *backgroundAudioPlayer;
 SystemSoundID burnRubberSoundID;
 BOOL touchInCar;
}
- (void) privateMethod;
–d

These methods are not really private, but are not visible in the header file. They are “private APIs.”