1

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!

SeniorShizzle
  • 984
  • 1
  • 11
  • 27
  • Thanks guys! I'm just amazed. I love Stack Overflow, I've never been anywhere else where you can get this much relevant help, and so quickly. – SeniorShizzle Jul 14 '10 at 06:58

2 Answers2

1

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
  • 4,417
  • 2
  • 24
  • 39
  • There is also a notification for DidEnterBackground if you do not want the logic in the app delegate. – drawnonward Jul 14 '10 at 06:15
  • Okay, so you're telling me to invoke NSUserDefaults on applicationDidEnterBackground: every time, and then only update from defaults on viewDidLoad? Genius! – SeniorShizzle Jul 14 '10 at 06:22
1

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
  • 27,575
  • 16
  • 91
  • 128