2011-03-09 74 views
2

我有一個plist,有一個數組的字典。在字典中有一個名爲UID的KEY。我想查詢UID =「1234」的plist ..我將如何搜索?查詢plist是一個字典數組

樣品

<array> 
    <dict> 
     <key>UID</key> 
     <string>1234</string> 
     <key>name</key> 
     <string>bob</string> 
    </dict> 
    .... 
</array> 
+0

[陣列從陣列使用詞典(的可能重複http://stackoverflow.com/questions/2680403/array-from-dictionary) – 2011-03-09 18:12:41

+0

@DavidGelhar:或許不是;看起來像@ magic-c0d3r想要*過濾*數組,而不是從每個對象中提取值。 – 2011-03-09 18:46:09

回答

5

讀取在作爲plist中字典的陣列,然後使用上NSArrayfilteredArrayUsingPredicate:方法:

NSString *path = [[NSBundle mainBundle] pathForResource:@"MyInfo" ofType:@"plist"]; 
NSArray *plistData = [NSArray arrayWithContentsOfFile:path]; 
NSPredicate *filter = [NSPredicate predicateWithFormat:@"UID = %d", 1234]; 
NSArray *filtered = [plistData filteredArrayUsingPredicate:filter]; 
NSLog(@"found matches: %@", filtered); 
1

讀取在作爲plist中字典的陣列,然後使用objectForKey:NSDictionary的方法。

NSString *path = [[NSBundle mainBundle] pathForResource:@"MyInfo" ofType:@"plist"]; 
NSArray *plistData = [[NSArray arrayWithContentsOfFile:path] retain]; 
for (NSDictionary *dict in plistData) { 
    if ([[dict objectForKey:@"UID"] isEqualToString:@"1234"]) { 
     NSLog(@"Found it!"); 
    } 
} 
+0

我試圖避免for循環,如果可能的話。這就是我現在正在做的。我想知道是否有替代方案。 – Arcadian 2011-03-09 19:29:47

+0

請參閱Dave DeLong的回答!他的解決方案應該工作得很好。 – 2011-03-09 19:30:29