Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
If you want to call a method exposed by an object, you do so by sending that object a message. The message consists of the method signature, along with the parameter information. Messages are enclosed in square brackets; the object receiving the message is on the left and the parameters are on the right, with each parameter following a colon. If the method accepts more than one argument, this is explicitly named, and the second parameter follows a second colon. This allows multiple methods with the same name and argument types to be defined
[anObject someMethod]; [anObject someMethod: anotherObject]; [anObject someMethod: anotherObject withAnotherArgument: yetAnotherObject];
The name of the method is the concatenation of the method name and
any additional named arguments. Hence in
the preceding code we have someMethod: and someMethod:withAnotherArgument:. This may seem odd to
people coming in from other languages, which usually have much
terser naming conventions, but in general, Objective-C method names are
substantially more self-documenting than in other languages. Method
names contain prepositions and are made to read like sentences. The
language also has a fairly entrenched naming convention, which means
that method names are fairly regular.
While Objective-C method names are long, Xcode will perform code completion as you type. A pop-up list of suggested methods will appear automatically. You can select a method using the up and down arrow keys, pressing Return to accept a suggestion. Pressing Control-/ will step you through the parameters of the method.
Methods can return output, as shown here:
output = [anObject someMethodWithOutput: anotherObject];
And they can be nested, as in the following:
output = [anObject someMethodWithOutput: [anotherObject someOtherMethod]];
When I originally started writing in Objective-C, one of the main problems I had with the language was the way it dealt with method calls. For those of us who are coming from more utilitarian languages, the behavior of Objective-C in this regard does seem rather strange. Although Objective-C code can be valid and not follow the rules I’ve described here, modern Objective-C is not really separable from the Cocoa framework, and Cocoa rules and conventions have become Objective-C’s rules and conventions.