Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
If you’ve never seen Objective-C before, the square brackets ([ and ]) might seem a little unusual. This is what is known as message passing syntax. Within the two square brackets are the target of a message and the parameters of that message.
The capability to send messages to objects is what lifts Objective-C above its roots in ANSI C and provides the robust, object-oriented functionality that Mac and iOS developers love today.
Let’s take an example from some code that we’ve already written:
NSString *stringB = [NSString stringWithFormat:@"%@ %@", @"Hello", @"World"];
By the Way
If you’ve had Quick Help active throughout the hour, notice what happens when you click the first letter of the method name; documentation for that method appears instantly. Now see what happens when you hit the escape key with the cursor still in that same spot—a list of all the possible messages that can be sent to an object or class! This list isn’t always as well-informed as the developer, so take its contents with a grain of salt.
In this line of code we are sending the NSString class the stringWithFormat: message. Note that the colon is considered part of the message name. In fact, all subsequent parameters are considered part of the name of the method being called. For example, if I had an ice cream object and I wanted to top it using a specific method, it might look something like this:
[iceCream topWithSauce:SauceHotFudge withCherry:YES withWhippedCream:NO];
In this line of code, what’s the name of the method we are invoking? It isn’t just topWithSauce: because that doesn’t convey what we’re actually doing. The method name is actually called topWithSauce:withCherry:withWhippedCream:
It might take some getting used to for programmers used to calling methods with a comma-delimited list of arguments as shown in the following line of C# code:
iceCream.Top(Toppings.HotFudge, true, false);
However, this syntax makes for highly readable, self-documenting code, and in many cases it removes all ambiguity about the name and purpose of a method’s parameters without needing to consult an external document.
As an exercise, go back through the code you’ve written so far this hour and for every use of square brackets, determine the target being sent the message and the name of the method being called.
By the Way
When you say the names of Objective-C methods out loud, you don’t pronounce the colons. Instead, insert a little pause between the parameter names as you read aloud.