How to Forward References in iOS Apps - dummies

How to Forward References in iOS Apps

By Rajiv Ramnath

During the development of your iOS app, you may want to forward a reference. This happens when you refer to a class (say A) in another class (say B) simply to declare an instance variable of the first class in the second class. One way to so is to include the interface file for A in the interface file for B.

However, this may result in circular dependencies if A and B have member variables of each other’s class. That is, an instance of A has a member variable that is an instance of B, and vice versa.

To get around these circular dependencies and also to simplify the use of one class in another, Objective-C provides what is known as a forward reference via a @class directive.

The @class directive sets up a forward reference to another class. Within the interface of PostfixCalculator (shown next), you see an example of a forward reference. The @class directive informs the compiler that the word StackOfInterface is the name of a class. So when the declaration of calculatorStack is compiled, the Objective-C compiler knows that this declaration is a valid declaration and also how to allocate memory for it.

This works because, when the compiler encounters a variable declaration, in order to allocate memory for an object-valued variable, it just needs to know that the variable is (a pointer to) an object of a class. The compiler doesn’t need to know details such as how the class’s methods are defined.

//------- @interface section -------
@class StackOfInteger; // forward declaration
@interface PostfixCalculator:NSObject
 @public NSString* expression;
 @protected StackOfInteger* calculatorStack;
 … Methods …

Practices for processes and a set of design criteria.