如何从NSArray中的每个NSDictionary获取特定键的所有值? [英] How can I get all values for specific key from each NSDictionary in an NSArray?

查看:259
本文介绍了如何从NSArray中的每个NSDictionary获取特定键的所有值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含字典对象的数组.在每本词典中,键是通用的.现在,我想获取该键的所有值.我已经通过迭代获得了这些值,但是我正在寻找一种可以直接完成此工作的简单方法或默认方法.

I have an array which contains dictionary objects. In each dictionary the key are common. Now I want to get all the values of that key. I have got these values with iteration, but I am looking for some straight forward way or a default method which does this job.

能否请您帮我得到一种达到目的的默认方法?谢谢.

Can you please help me to get one default method which serves the purpose? Thanks.

数据结构是这样的:

<array>
    <dict>
        <key>Match</key>
        <string>Football</string>
        <key>Stadium</key>
        <string>XXXXX</string>
    </dict>
    <dict>
        <key>Match</key>
        <string>HOCKY</string>
        <key>Stadium</key>
        <string>XXXXX</string>
    </dict>
 </array>

我现在正在这样做:

NSMutableArray * matches = [[NSMutableArray alloc] init];
        for (int i = 0; i< myArray.count; i++){
            [matches insertObject:[[myArray objectAtIndex:i] objectForKey:@"Match"] atIndex:i];
        }
        [matchDataArray addObjectsFromArray:matches];

它给了我正确的答案.但是我不想做这个迭代.我想要一个方法,该方法将从数组的所有索引中返回匹配"键的所有值,并立即保存在另一个数组中.新创建的数组将仅具有该数组所有索引中的Match键的值.

It gives me correct answer. But I don't want to do this iteration. I want a method which will return me all values of "Match" key from all indexes of array and save in another array at once. newly created array will have only the values of Match key from all indexes of array.

这可能吗?

推荐答案

使用键值编码有一个巧妙的窍门:

There's a neat trick with key-value coding that does it:

NSArray *matches = [myArray valueForKey: @"Match"];

这是一个实际的例子:

NSArray *anArray = @[
                      @{@"aWord" : @"I"},
                      @{@"aWord" : @"have"},
                      @{@"aWord" : @"an"},
                      @{@"aWord" : @"array"},
                      @{@"aWord" : @"which"},
                      @{@"aWord" : @"contains"},
                      @{@"aWord" : @"dictionary"},
                      @{@"aWord" : @"objects."},
                      @{@"aWord" : @"Etc."},
                      ];

NSArray *aWordArray = [anArray valueForKey:@"aWord"];

最后一行之后,aWordArray将包含与原始词典数组相同的单词.

After this last line, aWordArray will contain the words in the same order as in the original array of dictionaries.

这篇关于如何从NSArray中的每个NSDictionary获取特定键的所有值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆