How to Declare Public Methods in iOS App Development - dummies

How to Declare Public Methods in iOS App Development

By Rajiv Ramnath

Methods declaration for iOS apps may look bizarre to anyone who is more familiar with other languages, such as Java or C++. Just remember that all the public methods of the class are declared in the methods declaration section in the interface file, using the following format:

<-/+> <return type> <method name>: <list of parameters>

The initial – indicates that the method is an instance method. A + indicates that the method is a class method. Each parameter definition in the list of parameters looks like this:

<Parameter Label>:<Parameter Type> <Parameter Name>

Once again, look at the method in the interface specification for StackOfInteger:

@interface StackOfInteger:NSObject
 <Instance variables …?
 -(BOOL) isEmpty;
 -(void) push :(int) n;
 -(void) push2 :(int) intValue1 another:(int) intValue2;
 -(int) pop;

Note that for the first parameter — or if there’s only one parameter — the label is not provided. This is an example of a method in StackOfInteger (with two parameters):

 -(void) push2: (int) intValue1 another:(int) intValue2;

Remember there is a method (no pun intended) behind this madness. The labels make the method invocation more readable. For example, [anArray insertObject:anObject atIndex:5] is more readable than [myArray insertObject:anObject :5], where the meaning of the second parameter isn’t readily clear. Therefore, in the postfixall program

push2 :5 another:6;

is a little more understandable than

push2 :5 :6;

although both mean exactly the same thing.

Only public methods need to be declared in the interface file. Your program can contain private methods and C functions, as well. These don’t have to be declared in the interface file.

Note that the method CreateWithExpression is a class method that you can use in place of initWithExpression to create an instance of a PostfixCalculator already pre-initialized with a postfix expression.

Note that class methods aren’t the same as static functions that you might declare within your file. Class methods can be inherited and overridden by subclasses. Static methods can’t.

Interestingly, instance variables at the class level don’t exist in Objective-C. However, they can be simulated. For an example of how to do so, check out Instance Variables at a Class Level.

You can’t have two methods with the same name but a different number, or even a different order of parameters. In other words, method overloading isn’t possible, which isn’t like most of the common OO languages such as C++ and Java.