当postNotificationName:调用时,不发送NSNotification

时间:2010-01-21 22:29:55

标签: iphone objective-c nsnotificationcenter

我正在尝试使用NSNotificationCenteraddObserver获取postNotificationName的一个实例,但我无法理解为什么它不起作用。

我有2行代码来添加观察者并在2个不同的类中发送消息

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(newEventLoaded:) name:@"Event" object:nil];

[[NSNotificationCenter defaultCenter]postNotificationName:@"Event" object:self];

如果我将名称设置为nil它可以正常工作,因为它只是一个广播,当我尝试定义通知名称时,消息永远无法通过。

7 个答案:

答案 0 :(得分:12)

我的所有代码都使用NSNotifications,如此:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateView) name:@"ScanCompleted" object:nil];

[[NSNotificationCenter defaultCenter] postNotificationName:@"ScanCompleted" object:nil];

第一个是注册通知和第二个通知发布。

答案 1 :(得分:11)

基本上这与执行顺序有关。如果您在addObserver之前执行了postNotificationName,那么这是一个容易出现的问题。使用断点并逐步执行代码:)

你的第一个断点应该停在这里:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateView:) name:@"ScanCompleted" object:nil];

然后在这里:

[[NSNotificationCenter defaultCenter]postNotificationName:@"ScanCompleted" object:self];

此外,请确保选择器上有冒号。因为它的方法签名将是:

- (void)updateView:(NSNotification *)notification;

答案 2 :(得分:7)

我遇到了同样的问题。 原因是我在

调用了removeObserver方法
- (void)viewDidDisappear:(BOOL)animated{

    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];

   [notificationCenter removeObserver:self];

}

请检查您是否在postNotification之前调用了removeObserver。

提示:您可以搜索关键字“removeObserver”以查找是否已调用此函数。

答案 3 :(得分:5)

改变这个:

[[NSNotificationCenter defaultCenter]postNotificationName:@"Event" object:self];

到此:

[[NSNotificationCenter defaultCenter]postNotificationName:@"Event" object:nil];

如果您的第一个通知已正确注册,则应调用newEventLoaded。

答案 4 :(得分:4)

我有类似的问题,我的问题是由于在另一个线程上调用了通知。这解决了我的问题。

dispatch_async(dispatch_get_main_queue(),^{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"Event" object:self];
});

答案 5 :(得分:2)

你有没有尝试过任何其他名字,但是@“Event”和nil?可以肯定的是,您可以在一个文件中定义事件名称,并将其包含在通知注册和发送中。例如:

标题文件:

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];

答案 6 :(得分:1)

我成功修复了NSNotificationpostNotificationName:被称为“崩溃时未被发送。”

我发现真正的错误在通知消息处理程序中。

postNotificationNameaddObserver可以作为此主题的第一篇帖子。

相关问题