在第一个视图控制器中添加“addObserver”(NSNotificationCenter),在第二个视图中处理 [英] Add 'addObserver' (NSNotificationCenter ) in a 1st view controller, handle in 2nd
问题描述
我看到了一些关于在同一个类中添加观察者和句柄的例子,但我想知道的是,是否可以在第一个视图控制器中添加观察者并在第二个视图控制器中处理它?</ p>
我希望不断从第一个视图控制器发送距离并在第二个视图控制器中处理它。
第二个视图控制器作为子视图添加: addSubview
, addChildViewController
。
这就像在Android中广播一样。
是的,这是可能的。 NSNotificationCenter
完全按照这种方式工作。
首先,您必须在第一个视图控制器中注册监听器下面。
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(somethingHappens :) name:@notificationNameobject:nil];
}
- (无效)somethingHappens:(NSNotification *)通知
{
}
其次,从第二个视图控制器发布通知,如下所示。
[[NSNotificationCenter defaultCenter] postNotificationName:@notificationNameobject:obj];
系统会将通知广播给所有听众。
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.
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.
这篇关于在第一个视图控制器中添加“addObserver”(NSNotificationCenter),在第二个视图中处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!