I'm doing state miantainance code for Iphone os 4.0 using NSUserDefault class. when i click on home and then click on application then it works but when i click on home and then press on Build and Run button it doesn't work why is it so?
When you press the home button on iOS 4 the application is not stopped. It is suspended and put into a background state. The state of your application's UI is maintained automatically at this point.
When you hit build an go, the application is forcibly quit before being run again from Xcode.
I assume your code to save the UI state is in the applicationWillTerminate
method. If this is the case, then your code will never be run on iOS 4, since this method is no longer called, (at least that's the case I've seen from my own testing and from other people's experiences). And in the case where an app is forcibly quit (ie, by Xcode when hitting build and run), the applicationWillTerminate
method is bypassed.
You should, instead, implement the applicationDidEnterBackground
and applicationWillEnterForeground
methods.
This way, whenever the app is backgrounded, it will write it's state to the NSUserDefaults
, ensuring that the state is saved before the app is quit.
On iOS 4 the only way to actually fully quit an app is using the multitasking UI (double pressing the home button) which forcibly quits apps. This is why it's important to implement the backgrounding methods above since they will be much more likely to be executed.
As a last note, it might be worth calling synchronize
on the NSUserDefaults
instance just after you write your UI state, just to ensure the defaults are written to disk at that time.