我正在尝试检查xcode中plist文件中是否存在密钥。 我的plist文件有这种结构。
Root (Dictionary)
+- Parent1 (Dictionary)
- Key1 (Boolean)
- Key2 (Boolean)
- Key3 (Boolean)
- Key4 (Boolean)
+- Parent2 (Dictionary)
- Key1 (Boolean)
- Key2 (Boolean)
现在我需要检查在Parent1中是否存在Key2?我检查了NSDictionary,但无法知道如何做到这一点。
有关如何执行此操作的任何建议吗?
答案 0 :(得分:5)
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:@"your.plist"];
BOOL key2Exists = [[dict objectForKey:@"Parent1"] objectForKey:@"Key2"] != nil;
对于显式nil
比较,我有时会使用它,因为它使代码对我来说更具可读性(它提醒我语句左侧的变量是布尔值)。我也看过一个明确的“布尔演员”:
BOOL key2Exists = !![[dict objectForKey:@"Parent1"] objectForKey:@"Key2"];
我想这是个人偏好的问题。
答案 1 :(得分:1)
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:@"some.plist"];
NSDictionary *parentDictionary = [dictionary objectForKey:@"Parent1"];
NSSet *allKeys = [NSSet arrayWithSet:[parentDictionary allKeys]];
BOOL keyExists = [allKeys containsObject:@"Key2"];