Aff*_*ian 14 iphone objective-c nsnotificationcenter
我试图让使用的一个实例NSNotificationCenter与addObserver和postNotificationName,但我不能工作了,为什么它不会工作.
我有2行代码来添加观察者并在2个不同的类中发送消息
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(newEventLoaded:) name:@"Event" object:nil];
Run Code Online (Sandbox Code Playgroud)
和
[[NSNotificationCenter defaultCenter]postNotificationName:@"Event" object:self];
Run Code Online (Sandbox Code Playgroud)
如果我将名称设置为nil它工作正常,因为它只是一个广播,当我尝试定义通知名称时,消息永远不会通过.
Jam*_*uld 12
我的所有代码都使用NSNotifications如下:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateView) name:@"ScanCompleted" object:nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"ScanCompleted" object:nil];
Run Code Online (Sandbox Code Playgroud)
第一个是注册通知和第二个通知发布.
Pos*_*ism 11
基本上它与执行顺序有关.如果你在addObserver之前执行了postNotificationName,那么这是一个容易出问题的问题.使用断点并逐步执行代码:)
你的第一个断点应该在这里停止:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateView:) name:@"ScanCompleted" object:nil];
Run Code Online (Sandbox Code Playgroud)
然后在这里:
[[NSNotificationCenter defaultCenter]postNotificationName:@"ScanCompleted" object:self];
Run Code Online (Sandbox Code Playgroud)
此外,请确保选择器上有冒号.因为它的方法签名将是:
- (void)updateView:(NSNotification *)notification;
Run Code Online (Sandbox Code Playgroud)
我有同样的问题.原因是我调用了removeObserver方法
- (void)viewDidDisappear:(BOOL)animated{
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter removeObserver:self];
}
Run Code Online (Sandbox Code Playgroud)
因此,请检查是否在postNotification之前调用了removeObserver.
提示:您可以搜索关键字"removeObserver"以查找是否已调用此函数.
改变这个:
[[NSNotificationCenter defaultCenter]postNotificationName:@"Event" object:self];
Run Code Online (Sandbox Code Playgroud)
对此:
[[NSNotificationCenter defaultCenter]postNotificationName:@"Event" object:nil];
Run Code Online (Sandbox Code Playgroud)
如果您的第一个通知已正确注册,则应调用newEventLoaded.
| 归档时间: |
|
| 查看次数: |
25365 次 |
| 最近记录: |