Wednesday, February 16, 2011

Objective-C method call

Today I want to talk about method call in Objective-C.
One of the strangest things I came across when learning Objective-C was the method call syntax.
In C, we use something like this:
ObjectName->MethodName(parameter1, parameter2);

In Objective-C, the methods are called using messages, when we want to invoke a object method we send it a message.

Let's look at an example:

Suppose we have a NSTextField object named TextBox, to change its text we need to call its setStringValue method. In fact the method does not belong to the NSTextField, it is inherited from the NSControl (you can check the inheritances on the Mac OS X Reference Library).

So we have:
[TextBox setStringValue:@"New Text"];

As you can see we enclose the object name, method name and it's parameters in square brackets.
TextBox is the object name and setStringValue is the method name, but there is a little detail regarding the method name, setStringValue, besides identifying the method also identifies the first parameter of the method. The value of the parameter follows the parameter name after a colon. For methods with only one parameter we hardly notice this, but when a method has at least two parameters we really need to know what is going on.

Lets look at another example. Now suppose we have a calculator object and we want to call a method that receives a value and the operator. So if we want to add 25 to the current value we would call the method that we will call computeValue so to add a value we write something like this:

[Calculator computeValue:25 operator:Add];

On this example we can notice that the method name also refers to the parameter name.
Analyzing the code we can identify the object "Calculator", the method "computeValue" that also refers to the first parameter, and the second parameter "operator".

It's all for today. I hope this helped to clarify how the method call works.

No comments:

Post a Comment