在第一个视图控制器中添加“addObserver”(NSNotificationCenter),在第二个视图中处理 [英] Add 'addObserver' (NSNotificationCenter ) in a 1st view controller, handle in 2nd

查看:90
本文介绍了在第一个视图控制器中添加“addObserver”(NSNotificationCenter),在第二个视图中处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了一些关于在同一个类中添加观察者和句柄的例子,但我想知道的是,是否可以在第一个视图控制器中添加观察者并在第二个视图控制器中处理它?<​​/ 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆