Advanced Flow Control for Objective-C
- Objects and Messages
- Higher Order Functions
- From Functions to Messages
- Forwarding Messages
- Object Curry
- Concurrency
- Blocks
- Conclusion
When Apple introduced OS X, C or C++ was supported through Carbon and Objective-C or Java via the Cocoa APIs. With the 64-bit switch, Carbon started to go away, and the Java interface to Cocoa hasn't been updated for several years. When the iPhone was introduced, no other languages were supported for third-party developers. Objective-C is something of an obscure language. It was created in the 1980s and only really pushed commercially by NeXT. So what makes Apple love it so much for OS X development?
Learning Objective-C is very easy. If you already know C, Objective-C is just one extra syntactic structure and a handful of keywords. Being easy to learn is nice, but it's not enough. Learning any language (with the possible exception of Intercal or C++) is only a tiny fraction of the time you spend using that language. If it isn't easy to write the kind of code you want in that language, you'd be better off spending a few days learning a different language. In this article, we'll take a look at a technique that's very easy for languages in the same family as Objective-C, and much harder in others.
Objects and Messages
There's some debate over which language was the first true object-oriented language. The first to be called "object-oriented" was Smalltalk, in 1971. Many of the constructs in this language were superficially similar to those in Simula, which had appeared a few years earlier.
Objective-C is an example of the Smalltalk school of object-oriented programming. The object-oriented model for Smalltalk, proposed by Alan Kay, was that you had simple computers that communicated by passing messages. An important thing to note here is that classes are nowhere in the description. Classes are not required for object-oriented programming in the Smalltalk school. In Smalltalk, a class is just a kind of object that acts as a factory for others and handles method lookup. Newer languages in the Smalltalk family, such as Self and JavaScript, have no classes.
In the other branch of the object-oriented family, classes are very important. C++ was originally called "C with classes" and was intended to provide C with Simula-style support for abstract data types — very different from the Smalltalk model.
This distinction is very important because it means that, in the Smalltalk family, flow control is entirely under the developer's control. In Smalltalk, sending messages was the only way of moving control around your program. If you wanted a conditional statement, you sent an ifTrue: message to a Boolean object with a block (closure) object as the argument. Objective-C, inheriting static flow-control constructs from C, keeps a lot of the flexibility of Smalltalk.