0

to save some variables of my apps I use:

-(void)applicationWillTerminate:(UIApplication *)application {

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setFloat: self.viewController.sLabel.contentOffset.y forKey:@"floatKey"];    
[prefs setObject:self.viewController.newText forKey:@"stringVal"];
[prefs synchronize];

}

and to retrieve them, via a button, I do the following:

-(IBAction) riprendi:(id) sender {

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];  
float myFloat = [prefs floatForKey:@"floatKey"];

//some actions here

}

Everything is working on the simulator. However, using it on a real iPhone, the variables' saving and retrieving works just if you press the Home button, exiting the app and opening again but NOT if you switch off/on the iPhone. In this case, the variables get simply lost once you re-open the app...

What am I missing?? This is actually driving me crazy :(

Thank you so much ;) Fabio

  • Are you saying that A) turning the phone off *while your app is running* seems to cause the problem, or B) turning the phone off, even after you've closed the app, causes the prefs to disappear? – clint Apr 02 '09 at 15:59

2 Answers2

6

If you mean hitting the lock button on the top of the phone by saying "switching on/off", then it won't work, because locking the phone does not cause an application to quit. Your applicationWillTerminate: method is only called when you exit you're application to the home screen or to some other application. When the user presses the Sleep button, applicationWillResignActive: will be send to your application-delegate.

Apple's iPhone OS Programming Guide has a section on handling interruptions.

rincewind
  • 2,502
  • 19
  • 26
1

According to Apple's documentation

"NSUserDefaults caches the information to avoid having to open the user’s defaults database each time you need a default value."

If you want to make sure things are saved you should call "synchronize" on your prefs.

user684939
  • 11
  • 1