开发者

How to check for existence of a key in plist?

开发者 https://www.devze.com 2023-01-17 22:39 出处:网络
I am trying to check for the existence of a key in a plist file in xcode. My plist file has this structure.

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)
+开发者_Python百科- 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?


 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.


NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:@"some.plist"];
NSDictionary *parentDictionary = [dictionary objectForKey:@"Parent1"];

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

精彩评论

暂无评论...
验证码 换一张
取 消