save bool in nsuserdefaults

和自甴很熟 提交于 2019-12-05 05:41:41

No need to wrap it in an NSNumber, there are some convenience methods for this:

To set a BOOL, use:

[userDefaults setBool:YESorNO forKey:@"yourKey"];

To access it, use:

[userDefaults boolForKey:@"yourKey"];

[EDIT TO ANSWER YOUR ADDITIONAL QUESTION]

Not sure why you are using NSUserDefaults - it seems unnecessary for what you are trying to achieve? Here's what I would do for a button that can start/stop music:

-(IBAction)check 
{
    if (isQuiet)
    {
        // Play music
        // Change the button to indicate it is playing...
    } else 
    {
        // Stop music
        // Change the button to indicate it has stopped...
    }
    // Set your isQuiet to be the opposite of what it was when the button was clicked
    isQuiet = !isQuiet;
}

Box your BOOL value to NSNumber object and add it to NSUserDefault:

NSUserDefaults *boolUserDefaults = [NSUserDefaults standardUserDefaults];
[boolUserDefaults setObject:[NSNumber numberWithBool:isquiet] 
                     forKey:@"stringKey"];

Later you'll be able to retrieve that value as plain BOOL using -boolForKey: function in NSUserDefaults

To save:

[boolUserDefaults setObject:[NSNUmber numberWithBool:isQuiet] forKey:@"stringKey"];

When you read it back, read it as a NSNumber then do:

BOOL savedIsQuiet = [theNumberYouSaved boolValue];

Swift:

To save bool:

UserDefaults.standard.set(true, forKey: "storageKey")

To retrieve the bool:

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