NSUserDefaults - How to tell if a key exists NSUserDefaults - How to tell if a key exists ios ios

NSUserDefaults - How to tell if a key exists


objectForKey: will return nil if it doesn't exist.


As mentioned above it wont work for primitive types where 0/NO could be a valid value. I am using this code.

NSUserDefaults *defaults= [NSUserDefaults standardUserDefaults];if([[[defaults dictionaryRepresentation] allKeys] containsObject:@"mykey"]){    NSLog(@"mykey found");}


The objectForKey: method will return nil if the value does not exist. Here's a simple IF / THEN test that will tell you if the value is nil:

if([[NSUserDefaults standardUserDefaults] objectForKey:@"YOUR_KEY"] != nil) {    ...}