A key equivalent is a character bound to some view in a window, which causes that view to perform a specified action when the user types that character, typically while pressing a modifier key (in most cases the Command key). A key equivalent must be a character that can be typed with no modifier keys, or with Shift only.
An application routes a key-equivalent event by sending it first down the view hierarchy of a window. The global NSApplication object dispatches events it recognizes as potential key equivalents (based on the presence of modifier flags) in its sendEvent: method. It sends a performKeyEquivalent: message to the key NSWindow object. This object passes key equivalents down its view hierarchy by invoking the NSView default implementation of performKeyEquivalent:, which forwards the message to each of its subviews (including contextual and pop-up menus) until one responds YES; if none does, it returns NO. If no object in the view hierarchy handles the key equivalent, NSApp then sends performKeyEquivalent: to the menus in the menu bar. NSWindow subclasses are discouraged from overriding performKeyEquivalent:.
Some Cocoa classes, such as NSButton, NSMenu, NSMatrix, and NSSavePanel, provide default implementations of performKeyEquivalent:. For example, you can set the Return key as the key equivalent of an NSButton object and, when this key is pressed, the button acts as if it has been clicked. However, subclasses of other Application Kit classes (including custom views) need to provide their own implementations of performKeyEquivalent:. The implementation should extract the characters for a key equivalent from the passed-in NSEvent object using the charactersIgnoringModifiers method and then examine them to determine if they are a key equivalent it recognizes. It handles the key equivalent much as it would handle a key event in keyDown: (see “Overriding the keyDown: Method”). After handling the key equivalent, the implementation should return YES. If it doesn’t handle the key equivalent, it should either invoke the superclass implementation of performKeyEquivalent: or (if you know the superclass doesn’t handle the key equivalent) return NO to indicate that the key equivalent should be passed further down the view hierarchy or to the menus in the menu bar.
Last updated: 2007-03-16