当调用postNotificationName:时,NSNotification没有被发送。

2 浏览
0 Comments

当调用postNotificationName:时,NSNotification没有被发送。

我正在尝试使用NSNotificationCenteraddObserverpostNotificationName方法,但我无法弄清楚为什么它不起作用。

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

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

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

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

0
0 Comments

NSNotification not being sent when postNotificationName: called

在上述内容中,问题的出现可能是由于观察者没有正确注册通知或者通知的发送位置不正确导致的。解决方法可能是检查观察者是否正确注册了通知,以及确保通知在适当的位置发送。

在代码中,使用了NSNotificationCenter来注册和发送通知。注册通知的代码如下:

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

这段代码中,将观察者注册到了名为"ScanCompleted"的通知上,当该通知被发送时,会调用名为"updateView"的方法。然后,使用以下代码发送通知:

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

这段代码中,发送名为"ScanCompleted"的通知,不传递任何对象。

根据问题描述,代码看起来没有问题,但通知似乎不能正常工作。可能的原因是代码中其他地方存在问题,但通知中心本身的代码看起来是自包含的。可能需要检查多线程是否引起了问题,因为iPhone会自动进行多线程处理。

如果在选择器方法中使用NSLog语句,能否正常工作?如果方法没有参数,尝试将方法名设置为不带冒号的形式,比如:[[NSNotificationCenter defaultCenter]addObserver:self selector:(newEventLoaded) name:@"Event" object:nil];

根据测试,当将通知的名称设置为nil时,在选择的方法中使用NSLog语句是可以正常工作的。还尝试了方法是否带有参数和不带参数,结果都是一样的。

仍然不清楚为什么通知不起作用,但在重构代码后,使用相同的两行代码,按照文档的要求,现在通知已经可以正常工作了。

另外,确保在删除观察者时只移除特定的通知,而不是整个视图本身,比如只移除键盘隐藏的通知(例如keyboardDidHide)。这样,即使离开视图,仍然可以监听通知。

还有一种可能的情况是,观察通知的控制器没有被正确地强引用,导致在监听通知之前就被释放了。需要确保正确地引用观察通知的控制器。

希望以上内容能帮助解决类似问题的人们。

0
0 Comments

NSNotification not being sent when postNotificationName: called的问题出现的原因是调用了removeObserver方法。在viewDidDisappear方法中调用了removeObserver方法后,没有再次调用postNotification方法。解决方法是在调用postNotification方法之前检查是否调用了removeObserver方法。可以搜索关键字"removeObserver"来查找是否调用了该函数。

0
0 Comments

NSNotification not being sent when postNotificationName: called的问题出现的原因是因为执行顺序的问题。如果在执行addObserver之前执行了postNotificationName,那么就会出现这个问题。解决方法是使用断点和逐步执行代码来调试。

首先,在这里设置第一个断点:

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

然后在这里设置第二个断点:

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

另外,确保selector后面有一个冒号。因为方法签名应该是:

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

感谢提醒我postNotificationName在addObserver之前被调用。这解决了我的问题。

0