NSWindowControllerとESCキー

眠れぬ夜のために : OS X 用 Cocoa アプリケーションにおける環境設定ウィンドウの作り方( http://forthesleeplessnight.blogspot.jp/2012/10/os-x-cocoa.html)では、環境設定ウィンドウをESCキーでクローズする動作を、NSWindowのサブクラス化で実現している。

@interface PreferencesWindow : NSWindow
@end

@implementation PreferencesWindow

- (void) cancelOperation:(id)sender
{
  [self close];
}

@end

個人的にはNSWindowではなく、NSWindowControllerで以下のように実装するのが好みだ。

@interface PreferencesWindowController : NSWindowController
@end

@implementation PreferencesWindowController

- (IBAction) cancel:(id)sender
{
  [self close];
}

@end

delegateで拡張できるならば、subclass化よりもdelegateで拡張する方がCocoaらしいと思っています。