NSUserDefaults. setValue works, Not setBool

人盡茶涼 提交于 2019-12-01 16:18:47

How can you be sure its not working? I tried your code and it works for me. Are you sure you are reading the Boolean in the correct way AFTER you write it?

This code SHOULD work:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:NO forKey:@"test"];

[defaults synchronize];

BOOL myBool = [defaults boolForKey:@"test"];

I had the same problem by having the following code in my AppDelegate to keep track of whether the user had seen a particular viewController to display a walkthrough, and then setting this Bool to NO after the user had seen it.

if (![standardUserDefaults boolForKey:@"firstViewOfVC"]) {
        [standardUserDefaults setBool:YES forKey:@"firstViewOfVC"];
}

But then when you set it to NO later on and check if it "exists", you are actually seeing the NO boolean value and setting it back to yes. The quick fix is just to store the boolean value in an NSNumber object so that you can check for it's existence, independent of its value being YES or NO. See below:

if (![standardUserDefaults objectForKey:@"firstViewOfVC"]){
        [standardUserDefaults setValue:[NSNumber numberWithBool:YES] forKey:@"firstViewOfVC"];
    }

I had the exact same problem. Everything EXCEPT BOOLs were persisting correctly; but i was using some old coding styles from ios 3. recoded this way, everything works.

If anybody else is using old books.... here is an example

Bad stuff:

//////////// set / get bL2R
if (![[NSUserDefaults standardUserDefaults]
      boolForKey:kL2RomanizationChoice]) {
    [[NSUserDefaults standardUserDefaults]
     setBool:YES
     forKey:kL2RomanizationChoice];
    bL2R = YES;
    NSLog(@"L2Rom not found, set to YES.");
}
else {
    bL2R   = [[NSUserDefaults standardUserDefaults]
              boolForKey:kL2RomanizationChoice];
    NSLog(@"L2Rom found.");
    if (bL2R) {
        NSLog(@"L2Rom found to be YES.");
    }

}

Good stuff:

if (![defaults boolForKey:kL2RomanizationChoice])
    [defaults setBool:YES forKey:kL1RomanizationChoice];

L2String_Setting = [defaults objectForKey:kSecondLangChoice];
bL2R = [defaults boolForKey:kL2RomanizationChoice];

Update: sadly this only seemed to work briefly, and now is failing again... using Xcode 4.5.2. may just swap out bools for integers...

XCode 4.6 seems to have the same problem highlighted by hangzhouharry. A useful call is [[NSUserDefaults standardUserDefaults] dictionaryRepresentation] to see if your key values are looking the way they should.

For example -> autoLogout = 0;

which was set as a Bool, [settings boolForKey:@"autoLogout"] returns nothing

[settings integerForKey:@"autoLogout"] returns 0 (as, sort of, expected)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!