tags:

views:

42

answers:

2

How can I retain the state of an iPhone after it has exited. What is the easy way to do it?

+1  A: 

In your application delegate, you can define the -applicationWillTerminate: method to include code to save application state data.

- (void) applicationWillTerminate:(UIApplication *)application {
    // save state to data model here...
}

Your data model is up to you. For example, this could be a set of user defaults or a Core Data store.

The next time the app is started, you could check for saved state data in -applicationDidFinishLaunching: and initialize the app appropriately.

If you are using iOS 4 and your application supports multitasking features, you will get some of the state saving functionality "for free" because the app resigns focus, instead of terminating.

Alex Reynolds
Hi Alex,Thanks.Let me say, I have four tabs and currently I am in First tab and at sixth screen,(six navigations I have done), how can I store the info easily to identify, which one I should open when user opens the App, the next time. I assume that once the App is launched the next time, I will have to programmatically traverse tot that particular View? Is my assumption correct?
Krishnan
Correct, you save a "tree representation" of where your user left off, and then go back there when the app is relaunched.
Alex Reynolds
+2  A: 

The first question is when do you save? The answer is in two places (assuming you want to support 3.x and 4.x devices).

First, for OS 3.x devices (and OS 4 devices that don't multi-task):

- (void)applicationWillTerminate:(UIApplication *)application

And second, for OS 4.x devices:

- (void)applicationDidEnterBackground:(UIApplication *)application

You need to do this on iOS4 devices because if the app is shutdown while it's in the background it is just killed; you never see the applicationWillTerminate message.

As for the how, well it depends on how complex your app is. I created a simple protocol that I implement for each view controller that might want to save its state:

@protocol SaveState

- (NSData*) saveState;
- (id) initWithSaveState:(NSData*)data;

@end

It saves the state by looping through view controllers in the main navigation controller and calling the save state method. It then does the reverse in the applicationDidFinishLaunching: method. More information on my blog.

Stephen Darlington
Thanks Stephen. This really helped me. I will get back to you if I face any other problems.
Krishnan