嵌套父控制器中的调用方法

时间:2010-07-30 10:38:20

标签: iphone objective-c cocoa-touch

我有一个UIViewController,它有一个UIPopoverController,它有一个UINavigationController,然后是一个UIViewController。我如何从子UIViewController中调用父UIViewController中的方法(例如 - (void)update)?尝试了很多组合,但仍然无效。

2 个答案:

答案 0 :(得分:5)

在你的孩子身上:

@interface MyChildController:UIViewController {
    MyParentController *parent;
}
@property(nonatomic, assign) MyParentController *parent;
@end
@implementation MyChildController 
@synthesize parent;
...

在您的父控制器中,实例化您的孩子:

MyChildController *newChild = [[[MyChildController alloc] initWithNibName:nil bundle:nil] autorelease];

newChild.parent = self;

...

现在,在您的孩子中,您可以使用您父母的参考资料。例如,你孩子的一些方法:

- (IBAction)someAction {
    [self.parent doSomethingParentsDo];
}

答案 1 :(得分:1)

一种可能的方法是使用NSNotificationCenter。在父ViewController的viewDidLoad:方法中,将其注册为某个通知的观察者(我将在我的示例中使用@“DummyNotification”作为通知名称)。然后从子ViewController中的相应方法发布该通知。结果将如下所示:

ParentViewController.m

- (void) viewDidLoad
{
    /* existing code */
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(update) name:@"DummyNotification" object:nil];
}

- (void) update
{
    //method body
}

ChildViewController.m

//put this line wherever you want the ParentViewController to call -update
[[NSNotificationCenter defaultCenter] postNotificationName:@"DummyNotification" object:self];

参考:NSNotificationCenter Class Reference

此外,此问题被标记为iPhone,但Apple的UIPopoverController文档指出该类专门用于iPad,并且不能在其他设备上使用。这个问题标记错了吗?

参考:UIPopoverController Class Reference

相关问题