bdunagan
fill the void

Posted
17 August 2010 @ 10pm

Tagged
development

1 Comment

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;

1 Comment

[...] This post was mentioned on Twitter by Objective-C, solydzajs. solydzajs said: Cocoa Tip: NO vs nil for Preferences http://dlvr.it/3xFnl [...]


Leave a Comment