Event Handling

Earlier in this chapter, you learned that NSApplication, NSWindow, and NSView share a common parent class: NSResponder. This class plays a central role in the AppKit event handling system, as it declares the interface to any class that can respond to events.

To handle events, it is often sufficient to understand how to create a suitable subclass of NSResponder (a custom view, for example) and implement the relevant methods (e.g., mouseDown:). The application framework is responsible for ensuring that the appropriate method is invoked on the right object.

The event handling architecture is built on three major ideas: event messages, action messages , and the responder chain . As discussed earlier, events enter an application through the window server and are dispatched by NSApplication, with the method sendEvent:, to forward the event to the appropriate object.

The event model also deals with action messages. Objects, usually interface controls, create actions within the application that can be routed to a target object. The method used to dispatch action messages is NSApplication’s sendAction:to:from:. The sendAction: parameter is a selector for the action method to be invoked in the target, the to: parameter is the action’s target, and from: is the sender of the action. It is possible that the target is unspecified, in which case the action is sent up the full responder chain, and the first responder object that implements the message responds to it.

As for event handling, ...

Get Cocoa in a Nutshell 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.