One thing that keeps you a bit puzzled at the start of learning objective C is its function(method) declaration inside a class. Most of the developers who migrated from other languages like C , java, python, javascript etc may never have encountered with such use of function names.
Lets see an example
- (float) divideNumerator:(int)numerator withDenominator:(int)denominator{
/* Calculate and return result */
}
'-' tells that it is a instance method. To declare a class method, we will use '+' sign
(float) is the return type.
Now if you see the method name and argument, you will see a repetition of patterns like this. The pattern is repeated for all the arguments,
key:(return_type)value
For example:
divideNumerator:(int)numerator and
withDenominator:(int)denominator
Here the keys are divideNumerator and withDenominator whereas the values are numerator and denominator.
The method name is nothing but the combination of keys ending with colon, that is in this case, the method name is
divideNumerator:withDenominator:
In method with no argument, there is only one key with no values, for example
-(float)getResult{
/*Return result*/
}
In this case, the method name is
getResult:
Passing messages to a method.
In Objective C, an instance method called is termed as Passing message to the object. For examplefloat value = [obj divideNumerator:20 withDenominator:10];
Here the method divideNumerator:withDenominator: is called with arguments 20 and 10. The argument passed also have a key:value pattern, where keys are the same as mentioned in the method declaration.
No comments:
Post a Comment