bdunagan

bdunagan

August 17 2010
Cocoa Tip: NO vs nil for Preferences

Recently, I wanted to store a key/value pair in Info.plist or in preferences (NSUserDefaults) and know if the key existed and the value if it did. I started by using boolForKey, but this method doesn’t distinguish between NO and nil. Instead, I switched to valueForKey. Here are six lines of code to detect the three values:

NSDictionary *infoPlistDictionary = [[NSBundle mainBundle] infoDictionary];
BOOL doesKeyExistInPlist = [infoPlistDictionary valueForKey:PLIST_KEY] != nil;
BOOL isKeyTrueInPlist = [[infoPlistDictionary valueForKey:PLIST_KEY] boolValue] != NO;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
BOOL doesKeyExistInPrefs = [defaults valueForKey:PLIST_KEY] != nil;
BOOL isKeyTrueInPrefs = [[defaults valueForKey:PLIST_KEY] boolValue] != NO;
Cocoa Tip: URLs in NSTextFields Dedupe Files with 50 Lines of Ruby
LinkedIn GitHub Email