views:

270

answers:

1

In my app I'm using an NSUserDefaults object to store the username, password and server URL in the built-in Settings app. If there is no data saved, the user is presented a login interface and upon succesful login the username and password are saved. Then in my app I have a view which displays this information, but the text is missing as if the data hasn't been saved to the Settings yet. Here's the code:

...
NSUserDefaults* appSettings = [NSUserDefaults standardUserDefaults];
[appSettings setObject:username forKey:USERNAME];
[appSettings setObject:password forKey:PASSWORD];

if ( [appSettings synchronize] ) {

   // display an alert with a positive message
} else {
   // display an alert with a negative message

}

So, after logging in the positive message is displayed, but when I fetch the data again there is nothing there, unless I restart the app.

What do I need to do to save the data immediatly, or at least before another view controller needs to read the settings?

+2  A: 

The NSUserDefaults object stores its data in memory, and is a global object (to your application, anyway). Thus, anything you store in there should be immediately available to anything that tries to access it afterwards. You don't need to call synchronize here. If you're not getting your data, you should check the order of your calls to make sure they're being called when you think they are.

Ben Gottlieb
Aha! So I'm fetching the settings data in the awakeFromNib method in one of my controllers. I just set a breakpoint in that method and saw that it gets called immediatly, I tought it would all get called when the user clicks on the tab containing that particular view. awakeFromNib contains foreign code that was generating some static data, but I'll move it to viewDidLoad.Thanks Ben!
Lex