views:

189

answers:

1

I have a simple countdown timer that updates a label every second. How do I keep state or the illusion of it when hitting the home button or when the app gets put in the background?

+1  A: 

Actually, you don't need to run in the background if all you need to do is maintain a timer. In your app delegate's applicationWillTerminate:, create an NSDictionary containing the NSTimer's fire time and write it to a plist using -[NSDictionary writeToFile:atomically:], then read it back in using -[NSDictionary initWithContentsOfFile:] somewhere in your app delegate'sapplication:didFinishLaunchingWithOptions:.

If you are running in the background anyway, do the same in applicationDidEnterBackground: and applicationWillEnterForeground:. If you use this solution, be sure to invalidate the timer after you write the plist.

John Franklin
Thanks John, I'm trying this http://stackoverflow.com/questions/1587918/is-it-possible-to-save-the-state-of-a-timer-in-the-user-defaults. Pretty confused though, when pressing the home button does the app go into background or does it terminate? also when in the background, do NSTimers get invalidated?
Ronn
The behavior when pressing the home button is different between iPhone OS 3.x and iOS 4.0. In 4.0, applicationWillTerminate does not get called, and your app (usually) gets put in the background where the timers won't fire, but they aren't invalidated (unless you do that yourself in your suspend method); they'll start firing again if and when your app gets brought back to the foreground. But your app may also get killed and restarted.
hotpaw2
In your MyApp-Info.plist, the entry with raw key UIApplicationExitsOnSuspend (friendly value: Application Does Not Run In Background) determines which gets called, applicationWillTerminate: or applicationDidEnterBackground:. I don't believe timers get invalidated, but I'm not sure if they fire in the background or not. Any timers that have passed may all fire at once when the app becomes active. This behavior may also vary between the 2nd Gen iPod Touch and the iPhone 4.
John Franklin