Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Using NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];,

I use calls like BOOL boolFromPrefs = [defaults boolForKey:@"theBoolKey"]; To get a saved BOOL value.

If the key is not found, NO is returned (default behaviour of boolForKey).
But... NO can be a saved setting. Same thing for intForKey

So how can I test if a key exists before trying to get its value ?

like image 735
Oliver Avatar asked Mar 22 '11 20:03

Oliver


4 Answers

Check if the object exists before conversion to a BOOL.

if ([defaults objectForKey:@"theBoolKey"] != nil) {
    boolFromPrefs = [defaults boolForKey:@"theBoolKey"];
} else {
    boolFromPrefs = DEFAULT_BOOL_VALUE;
}
like image 26
MarkPowell Avatar answered Nov 14 '22 20:11

MarkPowell


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.

like image 157
Matthias Bauch Avatar answered Nov 14 '22 18:11

Matthias Bauch


I did it this way:

NSUserDefaults *prefs = NSUserDefaults.standardUserDefaults;
if ([[prefs dictionaryRepresentation].allKeys containsObject:@"yourKey"]) {
  float yourValue = [prefs floatForKey:@"yourKey"];
}
like image 24
Tim Autin Avatar answered Nov 14 '22 20:11

Tim Autin


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.

like image 8
Joe Avatar answered Nov 14 '22 19:11

Joe