【问题标题】:Communication between two not directly connected ViewControllers两个不直接连接的 ViewController 之间的通信
【发布时间】:2017-06-15 16:22:25
【问题描述】:

我想让 ViewController F 与 ViewController C 通信。 它们是这样排列的: 导航控制器 A 嵌入 ViewController B,它将 ViewController C 呈现在容器视图中。 从 ViewController B 到 NavigationController D 有一个转场,它嵌入了 ViewController E 和 ViewController F(在 E 和 F 之间转场)。

我当前的工作解决方案如下:在必要的 ViewController 之间建立一个委托“路径”:ViewController F 委托给 ViewController E,它委托给 ViewController B,最后将信息委托给 ViewController C。
感觉必须有一种更简单的方法来做到这一点。 你能推荐一个吗?也许将“segue path”内的 ViewController C 交给 ViewController F 以在 C 和 F 之间建立直接委托?

谢谢!

【问题讨论】:

  • communicate 是什么意思?运行方法?来回传递数据?响应事件?你的问题不清楚。有很多可能的方法,例如单例、委托、NSNotificationCenter
  • 在我的情况下,通信意味着:F 需要能够触发 C 的方法,并且还需要沿途传递数据。很抱歉这个不清楚的问题,感谢您指出这一点!

标签: ios objective-c uiviewcontroller delegation


【解决方案1】:

我会使用 NSNotification

在 ViewController F 中:

- (void)sendData {
    // Fire the notification
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ReceivedData" 
                                                        object:nil];   
}

在 ViewController C 中:

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

- (void)receivedDataNotification:(id)object {
    NSLog(@"Received Data!");
}

【讨论】:

  • 感谢您为我指明了正确的方向!我现在使用[[NSNotificationCenter defaultCenter] postNotificationName:@"ReceivedData" object:self userInfo:userInfo];
猜你喜欢
  • 2016-11-19
  • 2018-05-05
  • 1970-01-01
  • 2013-08-06
  • 2017-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-22
相关资源
最近更新 更多