2011-03-09 75 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