开发者

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 coul开发者_如何学运维d 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];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜