Delegation

Cocoa uses a technique called delegation to allow objects to specify other objects, called delegates , to handle certain messages for them. Thus, one object can delegate to another object the responsibility for handling messages of a certain type. Delegation gives the programmer a system for modifying or controlling the behavior of Cocoa’s more complicated objects, such as those of type NSApplication and NSWindow, without having to subclass them. Typically, delegation is used to control the behavior of an object or to invoke a method automatically in response to an action performed by a user.

An object sends its delegate specific messages under specific circumstances. Before the object sends the message, it checks to see if the delegate can respond to the message by interrogating the delegate with therespondsToSelector: message. If the delegate doesn’t implement a method for a specific message, the message simply isn’t sent! (The sender must interrogate the delegate, because if a delegate receives a message for which it doesn’t have a corresponding method, the program will generate an error.)

For more information about respondsToSelector: and similar messages, see the documentation for the NSObject class. The respondsToSelector: method is defined in the root NSObject class and thus is inherited by all other objects.

Should, Will, and Did Delegates

Cocoa has three principal types of messages that are sent to delegate objects: Should , Will, and Did messages. Both Should ...

Get Building Cocoa Applications: A Step by Step Guide 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.