KeyDown and Cocoa Sample

Andrea Girardi picture Andrea Girardi · Jul 17, 2009 · Viewed 9.4k times · Source

I'm learning how to build programs with Cocoa. I'm using a sample Apple application that records video from a webcam. I'd like to start and stop the video by capturing the key press. I've tried to override the keydown event but I've read that it's not possible in an NSObject. How can I handle this kind of event?

The class of application extends a NSObject class.

This is the code:

- (void)keyDown:(NSEvent *)event {
  NSLog(@"Hi there");
  NSString *characters = [event characters];
  if ([characters length]) {
    switch ([characters characterAtIndex:0]) {
      case NSUpArrowFunctionKey:
      NSLog(@"Key UP");
      break;
    }
  }
}

Answer

Peter Hosey picture Peter Hosey · Jul 17, 2009

I've tried to override Keydown event but I've read that It's not possible in an NSObject.

Correct. Only a responder can respond to events.

How can I handle this kind of event?

Implement a responder. Subclassing NSWindow or NSWindowController will work. Make sure you make your actual window or window controller an instance of your subclass.

The Cocoa documentation explains further.

The class of application extends a NSObject class.

Why? Normally, the principal class of the application bundle is NSApplication or a subclass of that—and there aren't many good reasons to subclass NSApplication.

PS: What's a very good book to start learn MacOS Programming?

I didn't learn by the Hillegass book, myself (I stuck to Apple's docs), but it's a very popular recommendation and I have read it and can tell you it's good.