所谓:NSNotification时postNotificationName送交
-
22-09-2019 - |
题
我试图让使用NSNotificationCenter
与addObserver
和postNotificationName
的一个实例,但我不能工作了,为什么它不会工作。
我有2行代码来添加观察者和在2点不同的类
发送消息[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(newEventLoaded:) name:@"Event" object:nil];
和
[[NSNotificationCenter defaultCenter]postNotificationName:@"Event" object:self];
如果我设置为nil
它的名字正常工作监守,它只是一个广播,当我试图定义一个通知名称中的消息从来没有得到过。
解决方案
所有我的代码使用NSNotifications
的像这样:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateView) name:@"ScanCompleted" object:nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"ScanCompleted" object:nil];
第一个是登记通知和所述通知的所述第二张贴。
其他提示
基本上它是所有做执行的顺序。如果你的addObserver之前执行postNotificationName,那么这是一个简单的问题有。使用断点和步骤通过代码:)
您第一个断点应该到此为止了:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateView:) name:@"ScanCompleted" object:nil];
然后这里:
[[NSNotificationCenter defaultCenter]postNotificationName:@"ScanCompleted" object:self];
此外,确保该选择器具有上冒号。因为它的方法的签名将是:
- (void)updateView:(NSNotification *)notification;
我有同样的问题。 其原因是,我称为removeObserver方法在
- (void)viewDidDisappear:(BOOL)animated{
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter removeObserver:self];
}
所以,请检查您是否如果早postNotification之前调用removeObserver。
提示:您可以搜索关键字“removeObserver”找到,如果你已经调用此函数
更改这样的:
[[NSNotificationCenter defaultCenter]postNotificationName:@"Event" object:self];
这样:
[[NSNotificationCenter defaultCenter]postNotificationName:@"Event" object:nil];
如果你的第一个通知是正确注册,newEventLoaded应该叫。
我也有类似的问题,我的问题是由于该通知被称为在另一个线程。这解决了我的问题。
dispatch_async(dispatch_get_main_queue(),^{
[[NSNotificationCenter defaultCenter]postNotificationName:@"Event" object:self];
});
您是否尝试过其他任何名字,但@“事件”和无?只是可以肯定,你可以在一个文件中定义的事件名称和包括到两个通知注册和发送。例如:
标题文件:强>
extern NSString * const NOTE_myEventName;
<强>源文件:强>
NSString * const NOTE_myEventName = @"MyEventName";
<强>注册强>
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(handleMyEvent:)
name:NOTE_myEventName
object:nil];
<强>通知发送:强>
[[NSNotificationCenter defaultCenter]
postNotificationName:NOTE_myEventName object:nil];
我成功固定我“NSNotification
未发送时postNotificationName:
称为”崩溃。
我找到了真正的错误是在通知消息处理程序。
在postNotificationName
和addObserver
都是权作为该线程的第一篇文章。