Justin Copeland
Justin Copeland

Reputation: 1951

How do I test if BOOL exists in NSUserDefaults user settings?

I set a BOOL value in NSUserDefaults as follows.

[userDefaults setBool:NO forKey:@"theKeyOfMyBOOL"];

Somewhere else in my code, I want to perform some action if the key "theKeyOfMyBOOL" is not set in NSUserDefaults. How do I verify whether this key was set? If I do

[userDefaults boolForKey:@"theKeyOfMyBOOL"];

then the value returned could be nil, which evaluates to false I believe, or the actual BOOL value of NO, which values to false.

However, I need to differentiate between these two values (as well as YES of course). How do I reliably do that?

Upvotes: 11

Views: 5445

Answers (1)

jrturton
jrturton

Reputation: 119242

[userDefaults boolForKey:@"theKeyOfMyBOOL"]; returns a BOOL, so either YES or NO (not nil).

Internally, it is stored as an NSNumber. So, if you call

[userDefaults objectForKey:@"theKeyOfMyBOOL"];

you will be given an NSNumber, if you have ever stored anything, or nil, if you have not.

Upvotes: 46

Related Questions