2010-09-27 74 views
0

我正在检查xcode中plist文件中是否存在密钥。 我的plist文件具有这种结构。如何检查plist中是否存在密钥?

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

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

现在我需要检查Key2是否存在于Parent1中?我检查了NSDictionary但无法得到如何做到这一点。

有关如何做到这一点的任何建议?

回答

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

至于明确nil比较,我有时是因为它使代码更易读,我(它提醒我,在语句的左侧的变量是一个布尔值)使用它。我也看到了一个明确的“布尔投”:

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

我想这是个人喜好的问题。

+0

'BOOL key2Exists = [subDict objectForKey:@“Key2”];'will do; '!= nil'位是多余的。 – 2010-09-27 09:38:30

+0

辉煌,工作,谢谢:) – raziiq 2010-09-27 09:41:51

+0

@Williham:如果不使用!=零,警告出现,所以我想它更好用!=零 – raziiq 2010-09-27 09:43:41

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

NSSet *allKeys = [NSSet arrayWithSet:[parentDictionary allKeys]]; 
BOOL keyExists = [allKeys containsObject:@"Key2"]; 
相关问题