【问题标题】:NSNotification is not calling @selector methodNSNotification 没有调用@selector 方法
【发布时间】:2015-12-02 18:19:39
【问题描述】:

我正在尝试将 NSString 从一个类传递到另一个类。假设我有 ViewController A 和 ViewController B。我想将 NSString 从 A 传递到 B。

在 ViewController A 中,我有以下代码:

[[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationMessageEvent" object:userType];

//这里的用户类型是我使用委托得到的字符串,我需要将此用户类型传递给ViewController B

在 ViewController B 中,我有以下代码: 在 viewDidLoad 中,我有以下代码:

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

//这个NSNotificationCenter方法被调用

我已经注册了以下选择器方法。

-(void) notificationAction:(NSNotification *) notification
{
    if ([notification.object isKindOfClass:[NSString class]])
    {
        NSString *message = [notification object];
        // do stuff here with your message data
        NSLog(@"%@ is message",message);
    }
    else
    {
        NSLog(@"Error, object not recognised.");
    }
}

//上面的选择器方法永远不会被调用。

我已经阅读了其他类似的 stackoverflow 答案,但我无法找到任何关于此的解决方案。

【问题讨论】:

  • 为了实际添加上述通知选择器,必须调用 ViewController B 的 viewDidLoad(也就是必须显示视图)
  • 感谢您澄清@Hayden Holligan。我实际上是在 B 之前加载 A。
  • 虽然您的代码有效,但请不要以这种方式使用通知对象。在这种情况下,对象是通知实例的发送者。使用 userInfo 在对象之间传递一些信息。
  • 在我的例子中,我在本地方法中创建了一个对象,所以观察者类在通知期间从另一个类触发。你可以检查这个:stackoverflow.com/questions/67328439/…

标签: ios objective-c iphone xcode nsnotificationcenter


【解决方案1】:

您的代码和语法显然是正确的。我猜这是对象生命周期的问题。我会假设以下任何一个都是正确的:

  • 在发布通知时,ViewController B 实际上并不作为对象存在

  • ViewController A 在 ViewController B 有机会注册之前发布通知。

您可以验证其中任何一个的一种方法是添加两个断点,一个是发布通知的位置,一个是注册通知侦听器的位置。应该在发布通知之前点击注册监听器的断点。如果发生这种情况,则在发布通知时验证 ViewController B 实际上是一个存在的对象(就像它没有从导航堆栈中弹出或其他东西一样)。

【讨论】:

  • 谢谢@Andy Obusek,我没有正确的 NSNotification 概念,我在 ViewController B 之前加载了 ViewController A,所以 ViewController B 无法注册 NSNotification 但我必须加载 ViewController A 在 ViewController B 之前,所以我认为 NSNotification 现在脱离了上下文,因为我无法在 A 之前加载 B。我可能会使用委托作为解决方法。谢谢
  • 那么解决方案是什么。对于我的应用程序,我需要在观察者控制器出现之前呈现后控制器。代表会解决问题吗?还是有不同的方法。
【解决方案2】:

这就是你要找的 NSNotification not being sent when postNotificationName: called 你必须在 postNotificationName 之前添加观察者

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多