How to Define Classes for iOS Applications - dummies

How to Define Classes for iOS Applications

By Rajiv Ramnath

In iOS development, the core concept of object-orientation (OO) is a class. A class definition in Objective-C comprises two parts, namely its interface and its implementation. They are explained here:

  • Its interface, which simply describes its components (that is, its methods and attributes)

    The interface file for Objective-C doesn’t declare a Java or C# type interface. Instead, it lists the methods and member variables of an Objective-C class.

  • Its implementation, which contains the actual code that makes up the class

For example, the interface for the PostfixCalculator class is

@interface PostfixCalculator:NSObject
 NSString* expression;
 StackOfInteger* calculatorStack;
-(id) initWithExpression: (NSString *) postFixExpression;
-(int) calculate;
-(NSString*) getExpression;

Consistent with the definition of this class, the interface for PostfixCalculator states that this class has the following:

  • Three methods:

    • initWithExpression

    • calculate

    • getExpression

  • Two member variables:

    • An expression that is an NSString object (or more correctly, a pointer to an NSString object)

    • A calculatorStack, which is a StackOfInteger object

Here is the interface for StackOfInteger:

@interface StackOfInteger:NSObject
 NSMutableArray* elements;
 int last;
 -(BOOL) isEmpty;
 -(void) push: (int) n;
 -(int) pop;

This class has two instance variables:

  • An array named elements (that stores the elements of the stack)

  • An integer named last

The class also has three methods: isEmpty, push, and pop.

As you can see, the interface directive is also where the name of the class is specified along with its superclass, if any. So, in abstract, an interface specification looks like this:

@interface <Class name> : <Superclass>
  Definitions of instance variables …
  Methods declarations …

In the StackOfInteger example, the name of the class is StackOfInteger, and it inherits from a class called NSObject (which is now the standard root class in iOS).