没有收到NSWindowWillCloseNotifications

Pet*_*ter 2 macos cocoa objective-c

在我正在创建的应用程序中,我有一个欢迎窗口,其中包含最近的文档列表(类似于新Xcode 4的欢迎窗口的功能).我在发布的欢迎窗口中注册了应用程序的委托和视图控制器NSWindowWillCloseNotification.不幸的是,只有应用程序委托才会收到此事件的通知.

我尝试了以下,所有行为都相同(窗口控制器未通知):

  • 删除AppDelegate的通知注册码,希望以某种方式"消费"通知.
  • 更改视图控制器上的方法-(void)windowIsClosing:,使其与应用程序委托的名称不同(相当长镜头,但我必须尝试)
  • addObserver:...ViewController中的调用移动到代码中的其他位置(因此在初始化程序期间不会调用它,如果某种程度上重要的话).
  • 我在其dealloc方法期间从通知中心取消注册我的视图控制器,但我确保在窗口关闭后不是在关闭期间调用dealloc方法.

我还试图在委托和控制器中监听其他事件,例如NSWindowWillMoveNotification,并再次通知委托但不通知视图控制器.我的视图控制器不是第一响应者链的一部分,但这应该无关紧要,因为我正在注册一个不希望处理无目标操作的通知.

因此,为什么我的控制器没有收到窗口关闭事件的通知,但我的应用代表是?

相关代码如下.... App代表:

@interface AppDelegate : NSObject <NSApplicationDelegate> {
}
@end

@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(windowClosing:) 
                                                 name:NSWindowWillCloseNotification 
                                               object:nil];
    // other initialization stuff
    [self showWelcomeWindow];
}

- (void)windowClosing:(NSNotification*)aNotification {
    // this method gets called when any window is closing
}
@end
Run Code Online (Sandbox Code Playgroud)

控制器:

@interface ViewController : NSObject {
}
@end

@implementation ViewController
- (id)init {
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(windowClosing:)
                                                     name:NSWindowWillCloseNotification
                                                   object:nil];
    }
    return self;
}

- (void)windowClosing:(NSNotification*)aNotification {
    // this method does not called when window is closing
}
@end
Run Code Online (Sandbox Code Playgroud)

Pet*_*ter 6

现在我已经弄明白了,回答我自己的后代问题.

NSNotificationCenter文档中所述:

请务必调用removeObserver:或removeObserver:name:object:在notificationObserver或addObserver中指定的任何对象之前:selector:name:is is deallocated.

ViewController对象正在监听关闭(NSWindowWillCloseNotifications)和我的数据模型对象的一个通知的窗口的通知.因此,当我在控制器上设置不同的模型对象时,我正在取消注册ViewController,而不是监听模型对象正在被取代.

不幸的是,我选择使用该removeObserver:方法(也将对象从窗口关闭事件的通知中removeObserver:name:object:删除),而不是更具体地从仅对象已注册的通知的子集中删除我的控制器.回顾代码,在removeObserver控制器对象之前需要通知来自模型以外的任何事件的事件之前编写.

故事寓意是让心理训练只[[NSNotificationCenter defaultCenter] removeObserver:self]在对象的dealloc呼叫期间使用,否则从非常具体的事件中取消注册(因为你不知道该对象将注册的其他事件通知).