7.6. Messaging

Now that you know about inheritance in Objective-C, you are ready to consider method invocation, or messaging. It is called messaging because it is like sending a message to an object, asking it to do something. Messaging has similarities to function calling, but it is important to realize that it is a higher-level operation: a single message will often entail several behind-the-scenes function calls.

When you send a message, like the following, a chain of events is set in progress:

[obj doSomething];

The function objc_msgSend is called, with the object and an identifier for the message doSomething passed as arguments. objc_msgSend is a function in the Objective-C runtime, which is a library of functions and data structures in every Objective-C program.

objc_msgSend performs a search for a function matching the arguments passed to it. It first looks in the class of obj, to see if a doSomething method has been defined there. If not, it moves to the superclass, to see if doSomething appears there. It then moves to the superclass of the superclass, and so forth, until a doSomething method is found. When doSomething is located, the corresponding function is called. If it is not found in any of the ancestors of the class of obj, an error occurs.

As you can see from this example, messaging is a high-level operation, often leading to several function calls. It is also very powerful, because a programmer can influence the messaging procedure in various ways. For example, ...

Get Beginning Mac OS® X Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.