I need to access to parentViewController after presentMoalViewController. This is my method that I call in the firstViewController to view the secondViewController:
- (void)viewData {
SecondViewController *viewCtrl = [self.storyboard instantiateViewControllerWithIdentifier:@"select_data"];
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewCtrl];
navigationController.navigationBar.barStyle = UIBarStyleBlack;
UIBarButtonItem *saveButton = [[[UIBarButtonItem alloc] initWithTitle:@"Save" style:UIBarButtonItemStyleDone target:viewCtrl action:@selector(saveData)] autorelease];
viewCtrl.navigationItem.rightBarButtonItem = salvaButton;
UIBarButtonItem *undoButton = [[[UIBarButtonItem alloc] initWithTitle:@"Undo" style:UIBarButtonItemStyleBordered target:viewCtrl action:@selector(backView)] autorelease];
viewCtrl.navigationItem.leftBarButtonItem = annullaButton;
[self presentModalViewController:navigationController animated:YES];
}
When I click on saveButton, I try to access to parentViewController in this way, but it not work:
- (void) saveData {
FirstViewController *parentView = (FirstViewController*)[[self navigationController] presentingViewController];
parentView.dataString = [[NSMutableString alloc] initWithFormat:@"new string"];
[parentView performSelectorInBackground:@selector(myMethod) withObject:nil];
[self dismissModalViewControllerAnimated:YES];
}
For
navigationController
you can declare a property called something likemyController
, then you have to initiate yournavigationController
like this:In your
parentViewController
Class you declare your MethodIn your
navigationController
you can then call[myController saveData];
This should work, if you have any questions, feel free to ask!It would be much better if you used a delegate/protocol in your second viewController that the first viewController could set itself as. You can find more info here Pass data back to the previous controller or simply doing a search. This design pattern is used virtually everywhere in iOS programming.
The big advantage is that then your second viewController becomes independent of whoever presented it, and can be easily reused. The technical term would be 'decoupling'.
Last time I did this I used notifications:
in your parent vc view didload:
You can access your parent view controller using following-