Reputation: 549
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?
Upvotes: 0
Views: 2649
Reputation: 2975
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:@"some.plist"];
NSDictionary *parentDictionary = [dictionary objectForKey:@"Parent1"];
NSSet *allKeys = [NSSet arrayWithSet:[parentDictionary allKeys]];
BOOL keyExists = [allKeys containsObject:@"Key2"];
Upvotes: 1
Reputation: 104095
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.
Upvotes: 5