tags:

views:

425

answers:

4

I have an app (a game) which saves data: game state, high scores, achievements, etc. Currently the app delegate does this on applicationWillTerminate:. After playing around with iPhone 4 for a bit, it seems that applications pretty much never terminate: they just run in the background forever, unless the user goes out of their way to quit them, or restart the phone.

So my question is, should I find another place to save my data, and if so, when?

+2  A: 

you can do so in the views diddisappear delegate method

-(void)viewDidDisappear:(BOOL)animated

{

//CODE FOR SAVING

}

Suriya
+1  A: 

You should save in applicationDidEnterBackground. Make sure to wrap your saving code with – beginBackgroundTaskWithExpirationHandler: and endBackgroundTask, since without that, you have less than a second (or something like that) before execution suspends.

Joachim Bengtsson
The method is applicaitonDidEnterBackground: and your app is already in the background when it's called. Also, your app will never suspend while it's in the applicationDidEnterBackground method call, only after it returns. However, you have only about 5 seconds to return from that method before the watchdog will terminate you.
Jason Coco
+5  A: 

To minimize the amount of time spent in the delegate method call, you should find a place that makes sense to save during the game (level completion, checkpoints, etc). You can also add a new delegate method to your application delegate which will be called when your application transitions to the background where you can duplicate some of the things you may have done previously in applicationWillTerminate:. The new delegate method to implement is -applicationDidEnterBackground:.

You will also receive a notification that the user switched back to your app as applicationWillEnterForeground:.

Jason Coco
+2  A: 

There are 2 App delegate methods you can use

applicationDidResignActive: //pausing the app, used when a msg comes up. if multitasking this wont help

applicationDidEnterBackground: // called in iOS 4 for when the app is in the background

you can see when it loads into the foreground using

applicationWillEnterForeground:

check out the reference for more info

Rudiger
didResignActive is a pretty good place too, though didEnterBackground should suffice.
Joachim Bengtsson
Yeah, think there is a couple more too.
Rudiger