iPhone: How can a child tell his parent to do some

2019-06-02 14:54发布

问题:

OK, I have a RootViewController.m and defined a method in there:

-(void)doSomethingParent
{
    NSLog(@"Parent is doing something after child has asked");
}

I then added a childViewController.view like so:

if (self.child == nil) {

    ChildViewController *cvc = [[ChildViewController alloc]
                                initWithNibName:nil bundle:nil];
    self.child = cvc;
    [cvc release];

}    
[self.view insertSubview: child.view atIndex:0];

Now, I thought it would be very useful indeed if I could call my doSomethingParent method from the child. So I thought I would do it like this:

 @implementation ChildViewController
@class RootViewController;


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [super doSomethingParent];

}

But xCode tells me that "-doSomethingParent" not found... but I put @class in there?! Shouldn't it find it? I don't want to import the whole thing as I thought @class would be sufficient to let the child know that the parent has a method called doSomethingParent...

I'd be very grateful for any suggestions. Thanks in advance!

回答1:

Set rootViewController object as the delegate of an object of childViewController type. And use that delegate from ChildViewController to pass messages to RootViewController.

Inside RootViewController, when you create your ChildViewController object do:

childViewController.delegate = self;

And in ChildViewController, when you want to pass a message then pass it to RootViewController as:

[delegate doSomething];

In your ChildViewController.h interface, declare an ivar:

id delegate;

Then use @property (in .h) and @synthesize (in .m) for getter and setter.

Then do the above.



回答2:

super is a reference to it's superclass, not the parent view controller. You will have to keep a reference to RootViewController and pass the message to it...

...Or code a protocol and set your RootViewController as delegate of the child, so the child would be able to pass messages to RootViewController.

I prefer the second way.



回答3:

Easy way (perhaps not the best way):

self.child = cvc;
cvc.myParent = self;  // give the child a reference to its parent