当postNotificationName:调用时,不发送NSNotification

Aff*_*ian 14 iphone objective-c nsnotificationcenter

我试图让使用的一个实例NSNotificationCenteraddObserverpostNotificationName,但我不能工作了,为什么它不会工作.

我有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)

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

  • Gah,你最终做了什么样的重构?我遇到了同样的问题而且麻木了.我甚至在注册后直接添加了postNotification,使用日志语句和断点来验证这些行正在执行..什么都没有 (4认同)
  • 这正是我所拥有的它拒绝工作,让我认为问题在其他地方,但通知中心似乎是完全自包含的代码.我不知道在哪里寻找可能导致问题的原因.线程可能吗?iPhone会自动多线程吗?从来没听说过. (3认同)

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)


Jia*_*iao 7

我有同样的问题.原因是我调用了removeObserver方法

- (void)viewDidDisappear:(BOOL)animated{

    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];

   [notificationCenter removeObserver:self];

}
Run Code Online (Sandbox Code Playgroud)

因此,请检查是否在postNotification之前调用了removeObserver.

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


Dav*_*wsy 5

改变这个:

[[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.