NSNotificationCenter: addObserver that is not self

余生颓废 提交于 2019-12-08 05:37:27

This is possible as long as you pass the pointer to your view controller as the observer. Here's an example:

//Go to the detail view
VC2ViewController *dvc = [self.storyboard instantiateViewControllerWithIdentifier:@"VC2ViewController"]; //ID specified in the storyboard
[[NSNotificationCenter defaultCenter] addObserver:dvc selector:@selector(notificationReceived:) name:@"MyNotification" object:nil];
[self.navigationController pushViewController:dvc animated:YES];

Then, you can post your notification as usual:

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

I just tested the above code and it worked fine for me, the following function was called in my detail view controller:

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

    NSLog(@"RECEIVED");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!