首页 > 解决方案 > NSNotificationCenter 永远不会执行

问题描述

这是我的代码。

在这里创建调用Example到 ViewController中的 Notification 的观察者

- (void)addObserverExample
{
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(example:)
                                             name:@"Example"
                                           object:nil];
}


- (void)example:(NSNotification *)notification{
   NSLog(@"Example!!!");
}

viewDidLoad注册我的观察员

- (void)viewDidLoad
{
  [self addObserverExample];
}

在我的第二个 ViewController 中。当点击一个按钮时执行此代码:

[[NSNotificationCenter defaultCenter] postNotificationName:@"Example" object:self.dictKeys userInfo:nil];

我遇到的问题是通知永远不会执行。

任何想法。

标签: iosobjective-cnsnotificationcenter

解决方案


根据您的问题为 NSNotificationCenter 创建了演示,它对我来说工作正常。这是该代码的链接:NSNotificationCenter Demo

- (void)viewDidLoad {
    [super viewDidLoad];

    [self addObserverExample];
}

- (void)addObserverExample
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(example:)
                                                 name:@"Example"
                                               object:nil];
}

- (void)example:(NSNotification *)notification{
    NSLog(@"Example!!!");
    NSLog(@"%@",notification.userInfo);
}

- (IBAction)btnFireNotification:(id)sender {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Example" object:nil userInfo:@{@"key" : @"value"}];
}

推荐阅读