Passing Messages
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"];
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.