How to call method on presenting view controller from modal view controller

Iowa15 picture Iowa15 · Aug 12, 2013 · Viewed 14k times · Source

I have a modal view controller that I called in from another view controller. Upon dismissal of the modal view controller, I want a method to be called on the view controller that presented that modal view. What is the easiest way to do this?

I tried doing this in my modal view controller: [(ParentViewController*)self.presentingViewController foo]; before calling [self dismissViewControllerAnimated:YES completion:nil];.

Xcode gives me an error saying foo isn't recognized, even though it is defined and prototyped in the controller. If your solution involves blocks, I really don't understand them so I would appreciate it if you would add more detail. Thanks.

ParentViewController.h

@interface ParentViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource>
{
    NewAssignmentViewController *newAssignmentViewController;
    TableViewDataSource *data;
}

-(void)foo;

@end

Answer

rdelmar picture rdelmar · Aug 12, 2013

You need to get a correct reference to your presenting controller like this:

ParentViewController *presenter = [(UITabBarController *)self.presentingViewController viewControllers][0]; // 0 is assuming that ParentViewController is in the first tab. Change if necessary
[presenter foo];

The other way to do it would be to use delegation, but that's an answer for another time.