【问题标题】:Getting a NSDictionary that has a particular key inside an array获取在数组中具有特定键的 NSDictionary
【发布时间】:2014-02-20 12:12:35
【问题描述】:

我有一个 NSDictionaries 的 NSArray。

字典有这样的键:颜色、数字、代码、描述和大小。

现在我有一个键,我想在数组中找到那个字典,一些神奇的命令,比如:

NSDictionary *oneDict = [get a dictionary from myArray where "code" is equal to "32"];

code是key,32是value。

我知道如何枚举数组并逐个搜索每个字典,但我知道objective-c 是一个装满“技巧”的袋子,并且可能存在一个“魔术命令”来从一个数组中手术提取该字典行。

有什么线索吗?

【问题讨论】:

    标签: ios iphone cocoa-touch nsarray nsdictionary


    【解决方案1】:

    您可以使用 indexOfObjectPassingTest 来获取对象索引:

    NSUInteger index = [myArray indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        NSDictionary* dict = obj;
        return [obj[@"code"] intValue] == 32;
    }];
    

    如果没有找到,结果将是 NSNotFound;

    【讨论】:

      【解决方案2】:

      这可以通过更简单的 NSPredicate 来完成:

      NSPredicate * predicate = [NSPredicate predicateWithFormat:@"code MATCHES[cd] %@", value];
      NSArray *result = [myArray filteredArrayUsingPredicate:predicate];
      

      结果数组将保存所有匹配该值的 NSDictionaries。 看看 NSPredicate documentation 很强大

      【讨论】:

        【解决方案3】:

        如果您打算多次查找并且不介意花一些时间进行设置,您可以创建一个字典,将code 的值映射到包含这些值的字典。即:

        NSDictionary * mapping = [ NSDictionary dictionaryWithObjects:myArray forKeys:[ myArray valueForKey:@"code" ] ]
        id answer = mapping[@"32" ] ;
        

        这仅适用于code 包含唯一值的情况。如果值不唯一:

        NSArray * codeValues = [ myArray valueForKey:@"code" ] ;
        NSIndexSet indexes = [ codeValues indexesOfObjectsPassingTest:^BOOL(id object){ [ object isEqual:@"32" ] } ] ;
        NSArray * matchingDictionaries = [ myArray objectsAtIndexes:indexes ] ;
        

        matchingDictionaries 将是一个包含字典的数组,其中code@"32"

        将这些示例中的@"32" 替换为您希望查找的code 值等。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-12-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多