19

The NSUserDefaults API documentation has the boolForKey: message which is described like this -

boolForKey:

Returns the Boolean value associated with the specified key.

- (BOOL)boolForKey:(NSString *)defaultName

Return Value If a boolean value is associated with defaultName in the user defaults, that value is returned. Otherwise, NO is returned.

Given that a [[NSUserDefaults standardUserDefaults] boolForKey:@"some_Key"] gives back a NO it can be either because the key does not exist or the key exists and has a boolean value NO. How can we differentiate? As of now, I can only avoid getting into this situation in the first place.

Kampai
  • 22,848
  • 21
  • 95
  • 95
NP Compete
  • 2,369
  • 2
  • 16
  • 15
  • http://stackoverflow.com/questions/1965765/iphone-dev-nsuserdefaults-check-for-boolean-existance . I so DID NOT find this one when i searched before. :) – NP Compete Dec 10 '10 at 11:28

2 Answers2

33

You are using the user defaults incorrectly. At the launch of your app, you are supposed to call -[NSUserDefaults registerDefaults:] with a dictionary that contains the default values for all preferences.

Then, if the user has not set a preference, -boolForKey will return the default value.

Ole Begemann
  • 135,006
  • 31
  • 278
  • 256
  • 4
    I wouldn’t go so far and say that he uses the user defaults incorrectly. Registering defaults is optional and in his situation probably more convenient, but Mike Abdullah’s answer just fits better. – Rafael Bugajewski Aug 28 '11 at 19:04
29

Use the -objectForKey: method as well. This will tell you whether the key exists.

Mike Abdullah
  • 14,933
  • 2
  • 50
  • 75