After experimenting with Objective-C for a while now, I find the language is gradually growing on me. It’s still a bit strange in some spots, and I have a lot left to learn, but it’s starting to make sense. One of the things I really like about the language is a feature lifted from Smalltalk: using “infix” syntax to send a message.
// invoking a MyCalculator method (by sending it a message)
int sum = [MyCalculator add:29 to:13];
In my previous post I touched on what it means to send a message in Objective-C. I explained that method calls on a class or object are mediated by a message dispatcher at runtime. This means that method calls are more involved than just dereferencing a function pointer. A lookup process occurs, the results of which are cached for subsequent messages. Objective-C is a superset of traditional C, so you can still call global functions without sending any messages. Messages only enter the picture when you start dealing with the object-oriented features of the language.
The message being sent above ends up causing a class method to be called on the MyCalculator class. Objective-C refers to them as “class” methods, not “static” methods like in C#. The name of the method is add:to: which might take a moment to digest. As you saw in the code snippet, the method name is broken apart and woven into the argument list. When you refer to the method, you add all of the pieces together, including the colons. If the method didn’t take any parameters you would omit the colon altogether.
Here’s the declaration of the MyCalculator class:
@interface MyCalculator : NSObject
+ (int) add:(int) left to:(int) right;
The + sign indicates that add:to: is a class method. The first (int) means that this method returns an integer. The rest of the line is the method name, intermixed with the argument list. I find this style of naming a method to be very intuitive, after getting used to it. I find myself thinking about naming methods based on the parameters much more carefully and making interesting decisions that I’d never make in C#.
In case you’re interested, here’s the implementation of the MyCalculator class:
+ (int) add:(int) left to:(int) right
return left + right;
See you next time!