Respond to Program-Generated Events

In an object-oriented application, many situations exist in which an object must know what’s going on with other objects in the system. In this section, you’ll learn about two techniques for this kind of object-to-object communication in Cocoa: delegation and notification. These design patterns are so widely used in Cocoa programming that a thorough understanding of the concepts involved is absolutely critical to prepare you for developing complex applications. In fact, you’ll use delegation and notification extensively to complete the advanced tutorials in Chapter 10, Chapter 12, and Chapter 13.

Delegation

You can think of delegation as a means by which an object’s behavior can be modified without needing to create a custom subclass. A delegate is a helper object that receives messages from another object when specific events occur. An object sends requests to its delegate, allowing the delegate to influence its behavior and aid in decision making.

For an object to delegate responsibility, it must declare a delegate outlet along with a set of delegate messages that will be sent to the delegate when “interesting” things happen. To become a delegate, an object must implement one or more of the delegate methods. There are several types of delegation messages, depending on the expected role of the delegate:

  • Some messages are purely informational, occurring after an event has happened. They allow a delegate to coordinate its actions with ...

Get Learning Cocoa 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.