Chapter 8. Event Handling

Graphical interfaces are driven by user events— mouse clicks and keystrokes. Most of an application’s time is spent waiting for the user to tell the application what to do next. However, a running application can also receive events not originating from the user interface, such as packets arriving over a network interface or timers firing periodically. In Cocoa, both types of events result in a message sent to an object in your application, as depicted in Figure 8-1.

A Cocoa application receiving events
Figure 8-1. A Cocoa application receiving events

This chapter focuses on events—both user- and program-generated—and how you intercept, handle, and coordinate them in Cocoa.

Events

Events in Cocoa are represented by instances of the NSEvent class. An event object can be queried to discover its window, the location of the event within the window, and the time the event occurred (relative to system startup). You can also find out which, if any, modified keys (such as Command, Shift, Option, and Control) were pressed. An event also contains the type of event it represents. There are many event types, falling primarily into the following categories:

Keyboard events

Generated when a key is pressed or released or when a modified key changes. Of these event types, key-down events are the most useful. When you handle a key-down event, you can determine the character or characters associated with the ...

Get Learning Cocoa with Objective-C, 2nd Edition 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.