iPhone - How to detect if a key exists in NSUserDefaults standardUserDefaults

孤者浪人 提交于 2019-11-29 21:03:42
Matthias Bauch

Do it the right way and register default values.

NSDictionary *userDefaultsDefaults = @{
    @"SomeKey": @NO,
    @"AnotherKey": @"FooBar",
    @"NumberKey": @0,
};
[NSUserDefaults.standardUserDefaults registerDefaults:userDefaultsDefaults];

do this before you use anything from NSUserDefaults. The beginning of application:didFinishLaunchingWithOptions: is a safe place.

You have to register the defaults each time the app launches. NSUserDefaults only stores values that have been explicitly set.

If you use default values you don't have to use a check for a "isFirstLaunch" key, like suggested in other answers.
This will help you when you roll out an update and you want to change the default value for a NSUserDefaults item.

Check if the object exists before conversion to a BOOL.

if ([defaults objectForKey:@"theBoolKey"] != nil) {
    boolFromPrefs = [defaults boolForKey:@"theBoolKey"];
} else {
    boolFromPrefs = DEFAULT_BOOL_VALUE;
}
Tim Autin

I did it this way:

NSUserDefaults *prefs = NSUserDefaults.standardUserDefaults;
if ([[prefs dictionaryRepresentation].allKeys containsObject:@"yourKey"]) {
  float yourValue = [prefs floatForKey:@"yourKey"];
}

You can test by using objectForKey: and if that is nil then it is not set. All boolForKey does it takes the NSNumber returned if any and returns a BOOL value.

I would recommend setting default values for any key that your application might use. You could do this in the application:didFinishLaunchingWithOptions: method. That way you will know that each value has been set.

Hint, set a key called "defaultsSet" to YES so that you only do this once. Also, remember to call [[NSUserDefaults standardUserDefaults] synchronize] to save the values.

Swift Example based on MarkPowell's answer

if (NSUserDefaults.standardUserDefaults().objectForKey("SomeBoolSetting") == nil) {
    NSUserDefaults.standardUserDefaults().setBool(true, forKey: "SomeBoolSetting")
    println("Bool WAS nil")
} else {
    var boolValue:Bool? = NSUserDefaults.standardUserDefaults().boolForKey("SomeBoolSetting")
    println("Bool WAS NOT nil \(boolValue)")
}

swift version of @Tim Autin 's answer:

if contains(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys.array, "chuiser_cook_orders_dirty") {
    println("exist")
} 

Dont Complicate it :

if([NSUserDefaults.standardUserDefaults  objectForKey:@"yourBoolKey"])
{
  // Object Already Stored in User defaults
}
else
{
   //Object not stored
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!