How to use NSWindowDidExposeNotification

不羁的心 提交于 2019-12-08 06:47:48

问题


I am trying to update another windows when the one becomes visible. So I found the NSWindowDidExposeNotification and tried to work with it, so I wrote in my awakeFromNib:

// MyClass.m
- (void)awakeFromNib {
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc addObserver:self
           selector:@selector(mentionsWindowDidExpose:)
               name:NSWindowDidExposeNotification
             object:nil];
}

and implemented the method

// MyClass.h
- (void)mentionsWindowDidExpose:(id)sender;

// MyClass.m
- (void)mentionsWindowDidExpose:(id)sender {
    NSLog(@"test");
}

But it never gets called which is odd. What do I do wrong here?


回答1:


Generally speaking, you would set up your controller as the window's delegate in order to receive these notifications, like so:

// MyClass.m
- (void)awakeFromNib {
    // note: this step can also be done in IB by dragging a connection
    // from the window's "delegate" property to your `MyClass` object
    [window setDelegate:self];
}

- (void)windowDidExpose:(NSNotification *)notification {
    NSLog(@"test");
}

Although, after reading here and here, windowDidExpose may not be your best bet. I would recommend trying the windowDidBecomeKey delegate method instead. That one is posted whenever your window gains "focus" (starts responding to user input) which may be the right time to show your second window.

Update: (in response to comments)

Apple's documentation (quoted below) indicates that NSWindowDidExposeNotification is only valid for nonretained windows, which, according to the posts that I linked above, are quite uncommon.

NSWindowDidExposeNotification

Posted whenever a portion of a nonretained NSWindow object is exposed, whether by being ordered in front of other windows or by other windows being removed from in front of it.

The notification object is the NSWindow object that has been exposed. The userInfo dictionary contains ... the rectangle that has been exposed.

On a higher level, NSNotification objects are simply packages of data that get passed around between Cocoa classes and NSNotificationCenter objects. NSNotificationCenter objects are controllers that manage these packages of data and send them out to observers as required. There is usually no need to trap notifications directly. You can simply use KVC/KVO or pre-defined delegates in your classes and Cocoa handles all of the dirty details behind the scenes.

See Notification Programming Topics and Key Value Coding Programming Guide if you want to know more.



来源:https://stackoverflow.com/questions/2723575/how-to-use-nswindowdidexposenotification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!