容器视图控制器与childViewControllers的通信

时间:2012-05-30 23:44:05

标签: ios cocoa-touch uiviewcontroller delegates

我有一个带有3个子UIViewController子类的容器视图控制器(添加了addChildViewController)。我希望我的一个子视图控制器在从容器视图控制器上删除某些内容时执行某些操作。我很难掌握这种沟通应该如何发生。如果我尝试创建一个委托,我的子视图控制器会出错,因为我会将两个子类互相导入。

2 个答案:

答案 0 :(得分:5)

听起来你正在解决正在编译你的应用程序的问题,因为互相.h文件importing,对吗?

  

编辑:再次阅读您的问题,我不是100%清楚哪个视图控制器需要调用另一个。如果我混淆了   在我的解决方案中父级和子级视图控制器的角色,只需切换   他们。以下技术可让您在任意两个视图之间进行通信   控制器(父母和孩子,兄弟姐妹和兄弟姐妹等)

有很多方法可以解决这个问题。如果你想使用delegate模式,你可以简单地重写标题以避免其中一个.h文件中的#import

ParentViewController.h:

#import "ChildViewController.h"

@interface ParentViewController: UIViewController {
@private
   ChildViewController* childVc;
}

- (void) doSomething;

ChildViewController.h

@class ParentViewController;   // NOT #import!

@interface ChildViewController: UIViewController {
@private
   ParentViewController* parentVc;
}

ChildViewController.m

#import "ParentViewController.h"

这应该避免使您的应用程序无法编译的循环依赖。

现在,尽管上述工作,我可能会选择另一种解决方案,为了清洁。使用protocol。父进程可以实现协议,然后子进程只需要有一个实现协议的委托:

#import "MyProtocol.h"

@interface ParentViewController: UIViewController<MyProtocol> {

}

- (void) doSomething;

在MyProtocol.h中:

@protocol MyProtocol
 - (void) doSomething;
@end

然后在ChildViewController.h

#import "MyProtocol.h"

@interface ChildViewController: UIViewController {
@private
   id<MyProtocol> delegate;
}

@property (nonatomic, assign) id<MyProtocol> delegate;

在ChildViewController.m中:

   [delegate doSomething];

或者,您可以完全避免使用委托,以及communicate between the controllers using NSNotificationCenter,这会使它们分离一些,并避免编译器循环(双向依赖)。

Here are the Apple docs on NSNotificationCenter

答案 1 :(得分:2)

你不能去:

MyChildViewController *myChildViewController = (MyChildViewController *)[self.childViewControllers objectAtIndex:0];
[myChildViewController doWhatever];

? 这应该允许您在数组childViewControllers的第一个索引(它是UIViewController上的属性)上向子视图控制器发送消息。