访问导航堆栈上的其他视图

时间:2009-08-05 14:40:28

标签: iphone objective-c

所以我有一个UINavigationController,显然它包含了我所有的ViewControllers。

我有三个。

根 - > View2-> VIEW3

所以我想知道以下可能......

当我'在'View3中(并且Root和View2的实例位于导航堆栈上)我是否可以调用View2或Root视图的任何方法/发送消息?

如果是这样,那怎么办呢?如果需要,我会发布一些示例代码。

谢谢,

乔恩

2 个答案:

答案 0 :(得分:4)

假设您在其中一个视图控制器中,您可以执行以下操作:

UIView* view2    = [self.navigationController.viewControllers objectAtIndex:1];
UIView* rootView = [self.navigationController.viewControllers objectAtIndex:0];

现在您可以向他们发送您想要的任何消息。

答案 1 :(得分:2)

NSNotification非常适合您想要松散耦合的对象。在Cocoa / iPhone上下文中,这意味着它们之间没有引用,主要是。

在可能收到消息的控制器中:

[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(doTheThing:) name: @"MessageBetweenControllers" object: nil];

在需要发送消息的控制器中:

NSDictionary *dict = [NSDictionary dictionaryWithObject: <some object> forKey: @"key"];
[[NSNotificationCenter defaultCenter] postNotificationName: @"MessageBetweenControllers" object: self userInfo: dict];

上面的示例只是一个模板(例如,NSDictionary位是可选的),但它显示了该机制。阅读有关NSNotification和NSNotificationCenter的文档以获取详细信息。

这不仅仅是理论上的。这是我在三个已发布的应用程序和我的新应用程序中用于对象间通信的主要方法。微不足道的通知开销。

两个陷阱:确保每封邮件只有一次addObserver - NSNotificationCenter不会剔除重复项;如果你插入两次相同的观察者,它将收到两次消息。另外,请确保在dealloc方法中执行removeObserver(再次参见docs。)