NSUserDefaults. setValue works, Not setBool

前端 未结 4 1707
春和景丽
春和景丽 2021-01-18 02:16

I trying to store some settings in NSUserDefaults, but It seems that the app won\'t store the setBool values.

This works:

[[NSUserDefaults standardUs

4条回答
  •  粉色の甜心
    2021-01-18 02:58

    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"];
        }
    

提交回复
热议问题