Messages and Methods
An Objective-C method is defined as part of a class. It has three aspects:
- Whether it’s a class method or an instance method
- If it’s a class method, you call it by sending a message to the class itself. If it’s an instance method, you call it by sending a message to an instance of the class.
- Its parameters and return value
-
As with a C function, an Objective-C method takes some number of parameters; each parameter is of some specified type. And, as with a C function, it may return a value, which is also of some specified type; if the method returns nothing, its return type is declared as
void
. - Its name
- An Objective-C method’s name must contain as many colons as it takes parameters. The name is split after each colon in a method call or declaration, so it is usual for the part of the name preceding each colon to describe the corresponding parameter.
Sending a Message
As you’ve doubtless gathered, the syntax for sending a message to an object involves square brackets. The first thing in the square brackets is the object to which the message is to be sent; this object is the message’s receiver. Then follows the message:
NSString* s2 = [s uppercaseString]; // send "uppercaseString" message to s ... // ... (and assign result to s2)
If the message is a method that takes parameters, each corresponding argument value comes after a colon:
[myStack1 push: @"Hello"]; // send "push:" message to myStack1 ... // ...with one argument, the NSString @"Hello"
To send a message ...
Get Programming iOS 4 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.