在我的 NSApp 委托(delegate)中,我添加了一个对象的观察者,该对象是 NSWindow 子类,该对象在委托(delegate)本身中启动,并在单击窗口后发布通知。选择器也在委托(delegate)中。从同一个委托(delegate)类中,我启动另一个对象,该对象在启动时将其自身添加为上面同一 NSWindow 子类的另一个窗口的观察者,并且选择器也位于这个新启动的类中。两个通知都已发布,但问题是它们都发布在两个类(class)中......这正常吗?我希望它只发布一次。
@implementation AppController
- (id)init
{
if (self = [super init])
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(toggleTestWindow:) name: @"TestNotification" object: testWindow];
return self;
}
- (void)toggleTestWindow: (NSNotification *)aNotification
{
if (!testWindow) {
testWindow = [[MyWindow alloc] init];
[mainWindow addChildWindow: testWindow ordered: NSWindowAbove];
} else {
[mainWindow removeChildWindow: testWindow];
[testWindow orderOut: self];
[testWindow release];
testWindow = nil;
}
}
@end
最佳答案
NSNotifications 可以按名称和实例进行过滤。为每个通知选择不同的名称,或者将每个观察者注册到它想要观察的特定对象实例。选择器只是告诉通知中心在确定观察者想要特定通知后调用什么方法。
注册观察者时,将要监听的实例作为对象参数传递。当您从该实例发布通知时,将 self 作为对象传递。
关于cocoa - 多个对象上的 NSNotification,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2659824/