ios 在第一个视图控制器中添加“addObserver”(NSNotificationCenter),在第二个视图控制器中处理
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17080605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add 'addObserver' (NSNotificationCenter ) in a 1st view controller, handle in 2nd
提问by Idan Moshe
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
.
我想不断地从第一个视图控制器发送距离并在第二个视图控制器中处理它。第二个视图控制器作为子视图添加:addSubview
, addChildViewController
.
It's something like broadcast in android.
这有点像android中的广播。
回答by taffarel
Yes it is possible. NSNotificationCenter
works exactly in that way.
对的,这是可能的。NSNotificationCenter
正是以这种方式工作。
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.
系统会将通知广播给所有听众。
回答by Second Front
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
还有另一种方法可以做到这一点(如果您想让其他视图控制器知道对象的值是否已更改)。您可以使用 KVO(键值观察):http: //developer.apple.com/library/ios/#documentation/cocoa/conceptual/KeyValueObserving/Articles/KVOBasics.html