Print Shortlink

Plain Old Objective-C Class – III

Methods in Objective-C support named parameters. You can specify the name of the parameter and assign value to it while invoking the method.
Let’s discuss this with a class Calculator that has a method add with three parameters num1, num2 and num3.

//Calculator.h
@interface Calculator : NSObject {
}
-(int)add:(int)num1 : (int)num2 : (int)num3;
@end

The add method accepts three parameters num1 an (int), num2 an (int) and num3 an (int). The parameter list is separated by colon (:). Let’s implement this method in Calculator.m and invoke it in the main function

//Calculator.m
@implementation Calculator
-(int) add:(int)num1 : (int)num2 : (int)num3{
    return num1+num2+num3;
}
@end

//main.m
int main(int argc, const char * argv[]){
 Calculator *calc = [Calculator alloc];
 int sum = [calc add:12 :12 :12];
}

In the line [calc add:12 :12 :12] you’re invoking add method by passing 12,12 and 12 as arguments. If you have a method that accepts 4-5 parameters method invocation code will not be readable at all. It’ll be better if you can specify the parameter name and pass a value to it, while invoking the method.
Let’s modify the add method to accept a name for the second and third parameters

//Calculator.h
@interface Calculator : NSObject { 
}
-(int)add:(int)num1  number2:(int)num2 number3:(int)num3;
@end

//Calculator.m
@implementation Calculator
-(int) add:(int)num1 number2:(int)num2 number3:(int)num3{
    return num1+num2+num3;
}
@end

We have introduced names for the second and third parameters number2 and number3. The syntax can be confusing to begin with. The method parameters are delimited by a colon(:) and you add a name before every colon. This is not the case for the first parameter of a method, though. You can invoke the add method in the main function as shown below.

int main (int argc, const char * argv[])
{
    Calculator *calc = [Calculator alloc];
    int sum = [calc add:12 number2:12 number3:12];
}

The add method call is a lot more readable now.
Understanding the named parameters concept in Objective-C is very essential to comfortably work with iOS applications.

Leave a Reply