views:

1014

answers:

4

I want to save the current tab the user is in when he/she quits the application so I can load the application with that tab highlighted when the user re-enters the app.

I presume I use the following method within my app delegate to save the current tab

- (void)applicationWillTerminate:(UIApplication *)application

but how do I gain access to the current tab - and what would be the best way to reload it?

A: 

UITabBarController has a property that will give you the index of the currently selected view controller; if you save that into NSUserDefaults on termination and restore it when the app starts again, that will restore the user's selection.

I'm purposely being vague here because the details of UITabBarController and NSUserDefaults are all in the documentation and you need to learn to read that before you ask others for help. Everything else you need should be in your Xcode documentation browser or, if you haven't installed the documentation, at http://developer.apple.com.

Brent Royal-Gordon
+5  A: 

In applicationWillTerminate, save the selectedIndex of the tabbarcontroller to your defaults.

  [[NSUserDefaults standardUserDefaults] setInteger:[tabBarController selectedIndex] forKey:@"tabBarIndex"];

Then on startup, read in index from NSDefaults and then set the tab.

    setIndex = [[NSUserDefaults standardUserDefaults] objectForKey:@"tabBarIndex"];
    [[NSUserDefaults standardUserDefaults] synchronize];

setIndex is an NSUInteger. Then set the TabBarController in your viewDidLoad like so:

[tabBarController selectedIndex:setIndex];

This is from memory, so you'll need to try it out, but this is the general approach.

Cheers, Jordan

Jordan
great it works - but it should be [[NSUserDefaults standardUserDefaults] setInteger:[tabBarController selectedIndex] forKey:@"tabBarIndex"];
zPesk
A: 

hi, I am using UITabbarController with 3 tabs, when i select second/Third Tab and close the application, while restoring the application i am getting the selected Tab, but it always showing the FirstTab content, why it is happening..

plz help me.

Sequence going on while restoring

my app having 3 tabs like FirstTab,SecondTab,Third Tab.

  1. First tab - ViewDidLoad (here i am having the logic for desiding which Tab to load)
  2. There it is going to ThirdTab(previously selected)- ViewDidLoad, ViewWillAppear 3.Then executest the FirstTab-ViewWill Appear.

thats y it is displaying the FirstTab data,

Plz help me how to show the selected data while restoring the View

thanks in Advance, koti [email protected]

A: 

Jordan's answer worked for me except that selectedIndex is a property, not a method; so:

tabBarController.selectedIndex = setIndex;
slinkp