zpesk
zpesk

Reputation: 4353

How do I save current tab bar item when user quits and reload to that item when restart?

I want to save the current tab the user is in when the user 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?

Upvotes: 3

Views: 1439

Answers (3)

slinkp
slinkp

Reputation: 3606

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

tabBarController.selectedIndex = setIndex;

Upvotes: 0

Jordan
Jordan

Reputation: 21760

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

Upvotes: 5

Becca Royal-Gordon
Becca Royal-Gordon

Reputation: 17861

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.

Upvotes: -2

Related Questions