How to Declare Instance Variables in iOS App Development - dummies

How to Declare Instance Variables in iOS App Development

By Rajiv Ramnath

Declaring instance variables for iOS apps requires that each instance has its own variable. Hence, the instance variables are created for each instance (in other words, each instance gets a copy of these variables).

In the PostfixCalculator class, the instance variables are

  • expression, which is (a pointer to) an NSString object

  • calculatorStack, which is (also a pointer) to a StackOfInteger object

The scope of a variable defines where it can be used. There are four options:

  • protected: Instance variables are visible and can be directly referred to (that is, used) in all instance methods of a class and any subclasses.

    protected is the default scope.

  • private: These variables are used only in the class that defined them.

  • public: These variables are visible to and can be used in any other class or method.

  • package: These variables are accessible only within the library in which they’re defined.

Take a look at an example from PostfixCalculator:

@interface PostfixCalculator:NSObject
 @public NSString* expression;
 @private StackOfInteger* calculatorStack;
 <Methods …>

Here, expression is declared as a public instance variable, whereas calculatorStack is declared as private.

Scopes other than protected aren’t used very frequently in Objective-C programs, partly because most folks don’t really understand them. Consider using one of the following two strategies:

  • Leave every variable as protected, and write accessor methods for those variables you want to make visible outside the class hierarchy.

  • To control access even more:

    • Explicitly declare variables as private.

    • Provide accessor methods for those variables you want to make accessible outside the class.

    If at all possible, stay away from annotating variables as public and package.

Incidentally, to access an instance variable in public scope, you use the pointer to member operator (aka the arrow operator ->). Say that the variable expression in the PostfixCalculator interface is declared as follows:

@public NSString* expression;

You access it like this:

myExpression = myCalculator->expression;

On the other hand, if the variable is declared as private (or the default of protected), you have to use an accessor method to get its value, as shown here:

NSString * myExpression = [myCalculator getExpression];

Some Objective-C compilers, such as the current gcc compiler on the Mac, don’t yet enforce private scope. Instead, they only generate a warning if you use a variable declared as private outside the class in which it’s declared. The warning is similar to the following:

warning: instance variable … is @private; this will be a hard error in the

On the other hand, the compiler inside Xcode does the right thing and says: Instance variable … is private.