Add 'addObserver' (NSNotificationCenter ) in a 1st view controller, handle in 2nd [duplicate]

女生的网名这么多〃 提交于 2019-12-19 06:19:14

问题


I saw a few examples about adding observer and handle in the same class, but what I want to know is if it's possible to add observer in first view controller and handle it in second view controller?

I want constantly send distance from first view controller and handle it in the 2nd one. The 2nd view controller added as a sub view: addSubview, addChildViewController.

It's something like broadcast in android.


回答1:


Yes it is possible. NSNotificationCenter works exactly in that way.

Firstly, you will have to register the listener in the first view controller as below.

-(void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(somethingHappens:) name:@"notificationName" object:nil];
}

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

}

Secondly, post the notification from the second view controller as below.

[[NSNotificationCenter defaultCenter] postNotificationName:@"notificationName" object:obj];

The system will broadcast the notification to all the listeners.




回答2:


There is another way to do this (in case you want to let other view controllers know if a value of an object has changed). You can use KVO (Key-Value Observing): http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/KeyValueObserving/Articles/KVOBasics.html



来源:https://stackoverflow.com/questions/17080605/add-addobserver-nsnotificationcenter-in-a-1st-view-controller-handle-in-2n

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