【问题标题】:Query plist that is an array of dictionary查询作为字典数组的 plist
【发布时间】:2011-03-09 18:05:05
【问题描述】:

我有一个包含字典数组的 plist。在字典中有一个名为 UID 的 KEY。我想查询 UID="1234" 的 plist .. 我将如何搜索?

样本

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

【问题讨论】:

标签: objective-c ios


【解决方案1】:

将 plist 作为字典数组读取,然后在 NSArray 上使用 filteredArrayUsingPredicate: 方法:

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);

【讨论】:

    【解决方案2】:

    将plist作为字典数组读入,然后使用NSDictionary的objectForKey:方法。

    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!");
        }
    }
    

    【讨论】:

    • 如果可能,我会尽量避免使用 for 循环。这就是我现在正在做的事情。我想知道是否有替代方案。
    • 见上面 Dave DeLong 的回答!他的解决方案应该可以正常工作。
    猜你喜欢
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-11
    • 1970-01-01
    • 2014-07-25
    • 1970-01-01
    相关资源
    最近更新 更多