开发者

How to use NSWindowDidExposeNotification

I am trying to update another windows when the one becomes visible. So I found the NSWindowDidExp开发者_运维问答oseNotification 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜