tags:

views:

47

answers:

2

Hey there.

I am trying to check for the existence of a key in a plist file in xcode. My plist file has this structure.

Root (Dictionary)
+- Parent1 (Dictionary)
   - Key1 (Boolean)
   - Key2 (Boolean)
   - Key3 (Boolean)
   - Key4 (Boolean)

+- Parent2 (Dictionary)
   - Key1 (Boolean)
   - Key2 (Boolean)

Now i need to check if Key2 exists in Parent1 or not? I checked NSDictionary but couldnt get how to do this.

Any suggestions on how to do this?

+3  A: 
 NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:@"your.plist"];
 BOOL key2Exists = [[dict objectForKey:@"Parent1"] objectForKey:@"Key2"] != nil;

As for the explicit nil comparison, I sometimes use it because it makes the code more readable for me (it reminds me that the variable on the left side of the statement is a boolean). I’ve also seen an explicit “boolean cast”:

BOOL key2Exists = !![[dict objectForKey:@"Parent1"] objectForKey:@"Key2"];

I guess it’s a matter of personal preference.

zoul
`BOOL key2Exists = [subDict objectForKey:@"Key2"];` will do; the `!= nil` bit is superfluous.
Williham Totland
Brilliant, that worked, thank you :)
raziiq
@Williham: If !=nil is not used, a warning appears, so i guess its better to use !=nil
raziiq
+1  A: 
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:@"some.plist"];
NSDictionary *parentDictionary = [dictionary objectForKey:@"Parent1"];

NSSet *allKeys = [NSSet arrayWithSet:[parentDictionary allKeys]];
BOOL keyExists = [allKeys containsObject:@"Key2"];
TomH