Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected results from NSUserDefaults boolForKey

Tags:

iphone

After uninstalling an application completely from the device and then loading it in the debugger, I am attempting in a setup method to load a flag using boolForKey. The first time the app runs I have the expectation that the bool will not exist, since I have just reinstalled the app. I expect from the documentation that boolForKey will therefore return NO.

I am seeing the opposite though. boolForKey is returning YES, which fubars my initial user settings. Any idea why this might be happening or a good way around it?

BOOL stopAutoLogin = [[NSUserDefaults standardUserDefaults] boolForKey:@"StopAutoLogin"];
_userWantsAutoLogin = !stopAutoLogin;

So stopAutoLogin comes out as "YES", which is completely unexpected.

Stranger and stranger: When I call objectForKey:@"StopAutoLogin" I get a nil object, as expected. It's just the boolForKey that returns a bad value. So I changed the code to this:

// this is nil
NSObject *wrapper = [[NSUserDefaults standardUserDefaults] objectForKey:@"StopAutoLogin"];

// this is YES
BOOL stopAutoLogin = [[NSUserDefaults standardUserDefaults] boolForKey:@"StopAutoLogin"];
like image 838
MahatmaManic Avatar asked Nov 15 '22 06:11

MahatmaManic


1 Answers

please try [UserDefaults synchronize];

Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes.

please see: http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html

like image 121
zh.chenghaojun Avatar answered Nov 23 '22 23:11

zh.chenghaojun