I need to know when my view controller is about to get popped from a nav stack so I can perform an action.
I can\'t use -viewWillDisappear, because that gets called
I tried this:
- (void) viewWillDisappear:(BOOL)animated {
// If we are disappearing because we were removed from navigation stack
if (self.navigationController == nil) {
// YOUR CODE HERE
}
[super viewWillDisappear:animated];
}
The idea is that at popping, the view controller's navigationController is set to nil. So if the view was to disappear, and it longer has a navigationController, I concluded it was popped. (might not work in other scenarios).
Can't vouch that viewWillDisappear will be called upon popping, as it is not mentioned in the docs. I tried it when the view was top view, and below top view - and it worked in both.
Good luck, Oded.
You can observe the notification:
- (void)viewDidLoad{
[super viewDidLoad];
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(navigationControllerWillShowViewController:) name:@"UINavigationControllerWillShowViewControllerNotification" object:nil];
}
- (void)navigationControllerDidShowViewController:(NSNotification *)notification{
UIViewController *lastVisible = notification.userInfo[@"UINavigationControllerLastVisibleViewController"];
if(lastVisible == self){
// we are being popped
}
}
I don't think there is an explicit message for this, but you could subclass the UINavigationController and override - popViewControllerAnimated (although I haven't tried this before myself).
Alternatively, if there are no other references to the view controller, could you add to its - dealloc?
Maybe you could use UINavigationBarDelegate's navigationBar:shouldPopItem protocol method.
Try overriding willMoveToParentViewController: (instead of viewWillDisappear:
) in your custom subclass of UIViewController
.
Called just before the view controller is added or removed from a container view controller.
- (void)willMoveToParentViewController:(UIViewController *)parent
{
[super willMoveToParentViewController:parent];
if (!parent) {
// `self` is about to get popped.
}
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
const BOOL removingFromParent = ![self.navigationController.viewControllers containsObject:self.parentViewController];
if ( removingFromParent ) {
// cleanup
}
}