How to detect if view controller is being popped of from the navigation controller?

aresz picture aresz · Feb 20, 2014 · Viewed 33.3k times · Source

I currently need to implement some code when the top view controller is being popped off from my navigation controller. Is there a way to detect when the view controller is being popped off the navigation controller stack?

As much as possible I want to stay away from using viewWillDisappear or viewDidDisappear because I'm using a splitview in my project, and selecting a different row in the master view will also trigger the viewWillDisappear/viewDidDisappear methods.

Answer

Nishant picture Nishant · Jul 20, 2016

You can detect whether a view is being popped using the isMovingFromParentViewController property for a view controller as shown below:

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if ([self isMovingFromParentViewController])
    {
        NSLog(@"View controller was popped");
    }
    else
    {
        NSLog(@"New view controller was pushed");
    }
}

isMovingFromParentViewController

Returns a Boolean value that indicates that the view controller is in the process of being removed from its parent.