I\'m trying to make my app remember which tab was last being viewed before the app quit, so that the app opens up to the same tab when it is next launched. This is the functiona
In the UITabBar's Delegate, overwrite
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
and store item's index in NSUserDefaults. Next time your app starts, read it from there, and set it back to being selected. Something like this:
-first, you would set a delegate for your UITabBar, like this:
tabBarController.delegate = anObject;
-in anObject, overwrite didSelectItem:
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
[def setInteger: [NSNumber numberWithInt: tabBarController.selectedIndex]
forKey:@"activeTab"];
[def synchronize];
}
Note that you save a NSNumber, as int values cannot be serialized directly. When you start the app again, it will read and set the selectedIndex value from the defaults:
- (void)applicationDidFinishLaunchingUIApplication *)application {
NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
int activeTab = [(NSNumber*)[def objectForKey:@"activeTab"] intValue];
tabBarController.selectedIndex = activeTab;
}