简体   繁体   中英

Call a method from a ModalView that is on the opener view

Basically I have a viewController that loads at app startup. In that VC, depending on whether there is userdata, I serve up a ModalView with either a login. After the user logs in, I can then dismiss the modalView, but I would like to call a method on the opener that will then populate a table with data.

I thought from the modalView I could do something like

[self.parentViewController loadInitialData];
[self.dismissModalViewControllerAnimated:YES];

but that does not work..

any suggestions?

The problem is because self.parentViewController is of type "UIViewController" and your -loadInitialData method doesn't exist in UIViewController. There are a couple of common ways to solve this problem... from easiest and least "correct" to most complicated and most "correct":

1) First you need to cast your self.parentViewController to the type of your parent view controller. Something like:

MyParentViewController *parentVC = (MyParentViewController*)self.parentViewController;
[parentVC loadInitialData];

2) You can add a property to your modal view controller that explicitly keeps a reference to your parent view controller and then call loadInitialData doing that.

@interface MyModalViewController : UIViewController {
    MyParentViewController *myParentViewController;
}

@property (nonatomic, retain) MyParentViewController *myParentViewController;

Then you can call:

[self.myParentViewController loadInitialData];

3) The most complicated, but most correct way to do it is to create a Delegate protocol, have your ParentViewController implement the protocol and have your modal view controller keep a reference to the delegate and call that way. Something like:

@protocol ManageDataDelegate

- (void) loadInitialData;

@end


@interface MyParentViewController : UIViewController <ManageDataDelegate> { ...


@interface MyModalViewController : UIViewController {
    id<ManageDataDelegate> delegate;
}

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

When you present your modal view controller, just set the delegate. In your MyParentViewController:

MyModalViewController *vc = [[MyModalViewController alloc] init];
vc.delegate = self;
[self presentModalViewController:vc];

Then in your modal view controller you can call back like so:

[self.delegate loadInitialData];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM