RK-
RK-

Reputation: 12201

Retain the State of iPhone Application after exit

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

Upvotes: 0

Views: 553

Answers (2)

Stephen Darlington
Stephen Darlington

Reputation: 52565

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.

Upvotes: 3

Alex Reynolds
Alex Reynolds

Reputation: 96927

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.

Upvotes: 1

Related Questions