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

Oliver picture Oliver · Mar 22, 2011 · Viewed 22.2k times · Source

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 ?

Answer

Matthias Bauch picture Matthias Bauch · Mar 22, 2011

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.