我正在XCode4中编写一个Cocoa / Objective-C应用程序,我需要知道我的首选项面板何时打开。我需要像windowDidBecomeKey这样的回调;我试图遵循this question提供的解决方案,但windowDidBecomeKey
或windowDidExpose
都不是代表方法(但其他人,如windowDidLoad
,windowWillLoad
等)。
为了明确我的意思,“不要作为委托方法出现”,我的意思是当我开始输入方法名称时,它们不会显示在自动完成中。无论如何我确实尝试过定义它们,但它们从未被调用过。
NSPanel
对象缺乏这些方法,还是有更多我需要做的事情?
目前,我有一个接口PrefWindowController
:
PrefWindowController.h:
#import <Cocoa/Cocoa.h>
@interface PrefWindowController : NSWindowController
//Delegate methods like windowDidBecomeKey appear to not be available here
@end
PrefWindowController.m:
@implementation PrefWindowController
- (id)initWithWindow:(NSWindow *)window
{
self = [super initWithWindow:window];
if (self) {
NSAlert *alert = [[[NSAlert alloc] init] autorelease];
[alert setMessageText:@".."];
[alert runModal];
}
return self;
}
- (void)windowDidLoad
{
NSAlert *alert = [[[NSAlert alloc] init] autorelease];
[alert setMessageText:@"Loaded"];
[alert runModal];
}
@end
当窗口在应用程序启动时从.xib加载时,windowDidLoad
将触发并显示上面定义的通知。我这样做只是为了测试方法实际上是被调用的。
有关如何在面板成为键或获得焦点时获得回调的任何建议将非常有帮助。
更新:
我在窗口控制器中添加了一个windowDidBecomeKey
方法,如下所示:
PrefWindowController.h:
- (void)windowDidBecomeKey:(NSNotification *)notification;
PrefWindowController.m:
- (void)windowDidBecomeKey:(NSNotification *)notification
{
NSLog(@"Test");
}
第一次打开窗口时会记录测试消息,但是在我的main.m
文件的返回行中,我收到错误消息:
线程1:程序接收信号:“EXC_BAD_ACCESS”
NSWindowDelegate协议具有以下方法
- (void)windowDidBecomeKey:(NSNotification *)notification
- (void)windowDidResignKey:(NSNotification *)notification
所以你可以将NSWindowController设置为NSWindow委托来获得这个回调。您还可以注册这些通知:
NSWindowDidResignKeyNotification
NSWindowDidBecomeKeyNotification
NSPanel是NSWindow的子类,因此所有这些行为都适用于您的情况。