开发者

Call method in nested parent controllers

开发者 https://www.devze.com 2023-01-10 01:26 出处:网络
I have a UIViewController that has an UIPopoverController that has an UINavigationCo开发者_如何学运维ntroller then a UIViewController. How can I from the child UIViewController call a method (eg. -(vo

I have a UIViewController that has an UIPopoverController that has an UINavigationCo开发者_如何学运维ntroller then a UIViewController. How can I from the child UIViewController call a method (eg. -(void)update) in the parent UIViewController? tried many combinations but still didn't work.


In your child:

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

In your parent controller, when instantiating your child:

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

newChild.parent = self;

...

now in your child you have a ref to your parent that you can use. For instance, some method in your child:

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


One possible approach would be to use NSNotificationCenter. In the viewDidLoad: method of the parent ViewController, register it as an observer of a certain notification (I'll use @"DummyNotification" as the notification name in my example). Then post that notification from the appropriate method in the child ViewController. The result will look something like this:

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];

Reference:NSNotificationCenter Class Reference

Also, this question is tagged as iPhone, but Apple's UIPopoverController documentation states that the class is used specifically for iPad, and will not work on other devices. Is this question tagged wrong?

Reference: UIPopoverController Class Reference

0

精彩评论

暂无评论...
验证码 换一张
取 消