views:

43

answers:

2

My application uses NSUserDefaults to store some values so that it can restore them on application update or if backgrounding is quit. Backgrounding automatically saves my integer values, but if the user quits the application from the launcher, the numbers are lost too, and the ViewDidUnload method I guess doesn't evoke when entering backgrounding. Is there a way that I can save the NSUserDefaults any time the application unloads. Also, the ViewDidLoad method had the same problem, it doesn't evoke from backgrounding. What's a way around this?

P.S. So far the only data my application needs to save is an int for an on-screen count.

UPDATE: UIApplicationDidEnterBackgroundingNotification works great with your suggestions!

+1  A: 

You can't save data right before it eventually gets killed, but you can save state 'just in case' in your applicationDidEnterBackground: app delegate.

There's also applicationDidBecomeActive:, but there's no reason to load your save data from there, since when it's invoked from an app that was in the background, the data will have been preserved any way.

Joost Schuur
There is also a notification for DidEnterBackground if you do not want the logic in the app delegate.
drawnonward
Okay, so you're telling me to invoke NSUserDefaults on applicationDidEnterBackground: every time, and then only update from defaults on viewDidLoad? Genius!
SeniorShizzle
+1  A: 

You can't tell if your app was launched from the background or not, at least how it's currently set up, since your app delegate will get the same sequence of events if it's launched from springboard.

As Joost says, you should save anything you need to restore state inside the applicationDidEnterBackground callback; essentially, you should assume this is the last message your app will get before it gets killed mercilessly by an evil process reaper.

You should check out the WWDC 2010 Session Videos, specifically, Session 105 - Adopting Multitasking on iPhone OS, Part 1 for a thorough explanation.

Shaggy Frog
Thanks for the Session Video suggestion! I love those videos and I'll check it out :)
SeniorShizzle