在 NSNotificationCenter 中遇到问题

Getting issue in NSNotificationCenter

从未调用 NSNotificationCenter 选择器方法。

通知如下:

- (IBAction)go:(id)sender {
AnotherViewController *obj = [self.storyboard instantiateViewControllerWithIdentifier:@"AnotherViewController"];

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




[self.navigationController pushViewController:obj animated:YES];

}

在 AnotherViewController.m 中观察通知:

  - (void)viewDidLoad {
[super viewDidLoad];

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


// Do any additional setup after loading the view.
  }

并且 receiveTestNotification 是:

- (void) receiveTestNotification:(NSNotification *) notification
{


if ([[notification name] isEqualToString:@"TestNotification"])
    NSLog (@"Successfully received the test notification!");
 }

问题是什么?谢谢

您应该将添加观察者方法移至视图控制器的初始化。因为您是在 AnotherViewController 注册自己接收通知之前发布通知。

   - (instancetype)initWithCoder:(NSCoder *)aDecoder
    {
        self = [super initWithCoder:aDecoder];
        if (self) {
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(receiveTestNotification:)
                                                         name:@"TestNotification"
                                                       object:nil];
        }
        return self;
    }