I have a mainViewController. I call [self pushModalViewController:someViewController] which makes someViewController the active view.
Now I want to call a function in mainViewController as someViewController disappears with [self dismissModalViewController].
viewDidAppear does not get called probably because the view was already there, just beneath the modal view. How does one go about calling a function in the mainViewController once the modalView dismisses itself?
Thanks a lot!
Using exit (unwind) segue
When you're using storyboards and segues you can use a very handy approach with minimal code to a dismiss modal view controller and inform the underlying view controller that the modal view controller has been closed.
Using exit (unwind) segues you gain 3 advantages:
prepareForSegue:
Implement it with only 2 steps
Swift
Objective-C
unwindFromSegue:
to your button and select action.You're done! Now the modal view controller closes when you click the
dismiss
button andunwindFromSegue:
informs your underlying view controller that the modal view controller has closed.Here's a callback solution which takes less modifications to your modal and parent: In the Model's .h add:
In the Model's .m put this in the completion when you dismiss the modal:
In the parent view controller when you instantiate your modal set the dismissed callback:
This answer was rewritten/expanded to explain the 3 most important approaches (@galambalazs)
1. Blocks
The simplest approach is using a callback
block
. This is good if you only have one listener (the parent view controller) interested in the dismissal. You may even pass some data with the event.In MainViewController.m
In SecondViewController.h
In SecondViewController.m
2. Delegation
Delegation
is the recommended pattern by Apple:MainViewController
In MainViewController.h
Somewhere in MainViewController.m (presenting)
Somewhere else in MainViewController.m (being told about the dismissal)
SecondViewController
In SecondViewController.h
Somewhere in SecondViewController.m
(note: the protocol with didDismissViewController: method could be reused throughout your app)
3. Notifications
Another solution is sending an
NSNotification
. This is a valid approach as well, it might be easier than delegation in case you only want to notify about the dismissal without passing much data. But it's main use case is when you want multiple listeners for the dismissal event (other than just the parent view controller).But make sure to always remove yourself from NSNotificationCentre after you are done! Otherwise you risk of crashing by being called for notifications even after you are deallocated. [editor's note]
In MainViewController.m
In SecondViewController.m
Hope this helps!