NSNotificationCenter从未执行过

问题描述 投票:0回答:2

这是我的代码。

在这里创建名为Example的Notification观察者到ViewController中

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


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

来自viewDidLoad注册我的观察员

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

在我的第二个View Controller中。点击按钮时执行以下代码:

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

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

任何的想法。

ios objective-c nsnotificationcenter
2个回答
0
投票

根据您的问题为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"}];
}

0
投票

我相信你遇到的问题可能与你的第二个视图控制器中你在self.dictKeys参数中传递object这一事实有关。如果要通过NSNotificationCenter传递数据,则应使用userInfo参数。

Darshan的例子以正确的方式做到了这一点。

© www.soinside.com 2019 - 2024. All rights reserved.