The -viewWillDisappear method: this is not the best place to change the view controller stack for your navigation controller, because it works both when switching tabs and when displaying a view on top of it.
I played around a bit with this and found that the best place for this is the method - [UITabBarControllerDelegate tabBarController: didSelectViewController:]. So, first you need to set the object as a delegate for the tab bar (I used the application delegate). Bind the delegate property of your UITabBarController to an object that implements the UITabBarControllerDelegate protocol in code or in Interface Builder.
Then we implement the -tabBarController: didSelectViewController: method. The trick now is how to say when the address book tab is switched. I tracked the view controller for the tab in question using a property of type UINavigationController (the root view controller for the tab). After binding the tab1NavController property to the actual instance using Interface Builder, you can use it to compare with the viewController parameter to see which tab was selected only.
@interface Pop2RootTabSwitchAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate> { UINavigationController *tab1NavController; } @property (nonatomic, retain) IBOutlet UINavigationController *tab1NavController; @end @implementation Pop2RootTabSwitchAppDelegate - (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController { NSLog(@"[%@ tabBarController:%@ didSelectViewController:%@]", [self class], tabBarController, viewController); if (viewController == tab1NavController) { NSLog(@"viewController == tab1NavController"); [tab1NavController popToRootViewControllerAnimated:NO]; } }
source share