Objective-C used to be the go-to programming language when developing software for iOS or macOS.
Objective-C was built on top of the C-language and added object-oriented capabilities and message passing between objects.
As it’s a superset of C, we can use C code in Objective-C classes.
Message passing is a technique used for invoking behavior by sending messages to an object rather than invoking the method by name.
Messaging in Objective-C follows a well-known design pattern called Chain of Responsibility. The main idea is to pass a request to a list of linked objects. The request travels until one of the receivers processes it. It can also happen that none of the objects responds to the request.
For messaging to work, each object contains an isa pointer, which is a pointer to the object’s class structure. This pointer gets initialized upon creating the object.
Every class structure includes a pointer to its superclass. The topmost superclass is the NSObject class.
Each class structure has a dispatch table. This dispatch table consists of entries that map messages – called method selectors, to method pointers.
Let’s assume that we send the message description to a button object, which is a UIButton instance:
The messaging system retrieves the object’s class structure through the isa pointer. The button object is a UIButton instance, and this class implements the method that can respond to the selector “description.”
We can check whether a class responds to a selector by invoking the class method instancesRespondToSelector: directly on the object’s class:
(lldb) po [UIButton instancesRespondToSelector:@selector(description)]
If the method selector is found in the class’s dispatch table, the corresponding method gets called. Otherwise, the search continues in the superclass.
Given the UIButton class, this means that the lookup bubbles up through the UIControl, UIView, and UIResponder classes.
UIButton -> UIControl -> UIView -> UIResponder -> NSObject
This lookup goes on until we reach the NSObject class. If the method selector is not found in the given object’s class hierarchy, no method call occurs.
Objective-C has been around since the 1980s. Apple released version 2.0 in October 2007. Objective-C 2.0 brought syntax enhancements and features like fast enumeration, blocks and class extensions.
Automatic Reference Counting, a compiler feature that simplifies memory management to a great extent, was introduced in 2010. Most developers expected further improvements and a version 3.0 of the programming language.
However, Apple had different plans. Chris Lattner started working on a new project at Apple, which eventually became one of the biggest surprises announced at WWDC 2014.