Catching Keyboard Eventsfor Our Calculator

In the remainder of this chapter, we’ll make our Calculator easier to use by taking advantage of our new knowledge of events and responder chains. The goal will be to let the user type digit keys (e.g., “5”) on the keyboard instead of clicking buttons in the Calculator’s window.

Tip

Some of the functionality that we will implement in the following sections could be implemented from within IB by assigning a key equivalent for each NSButton in the NSButton Info dialog. We’ve chosen to show you this approach instead for several reasons. First, we feel that this example shows many interesting details about Cocoa, including how the NSArray and NSDictionary classes operate. This example also shows how Objective-C allows you to “reach inside” the Cocoa classes, even though you don’t have their source code, and to change or augment the way that they operate. Finally, some of the functionality that we describe — the automatic enabling and disabling of keys depending on the current radix — cannot easily be implemented from within IB.

Subclassing the NSWindow Class

We’ll accomplish our goal by first subclassing the NSWindow class to form a new class called CalcWindow, then changing the class of our Calculator window to CalcWindow. Subclassing NSWindow is a common technique for intercepting all of the events that are destined for a window, rather than for a particular view in that window. (This example is slightly contrived, because Cocoa also allows ...

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.