开发者

Retain the State of iPhone Application after exit

How can I retain the state of an iPhone after it has exited. Wha开发者_如何转开发t is the easy way to do it?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜