【问题标题】:Searching on an array of array of dictionaries by a key通过键搜索字典数组
【发布时间】:2014-10-09 12:52:58
【问题描述】:

我有这样的字典

  NSDictionary *dictA = @{ @"name" : @"John",
                           @"city" : @"Los Angeles" };

  NSDictionary *dictB = @{ @"name" : @"Bob",
                           @"city" : @"Los Angeles" };

  NSDictionary *dictC = @{ @"name" : @"Carl",
                           @"city" : @"Dallas" };

像这样的几十个字典被城市分开,放在其他字典里

  NSArray *losAngeles = @[ dictA, dictB, ....];

  NSArray *dallas = @[ dictC, ... ];

一切都在一个数组中

self.arrayAll = @[losAngeles, dallas, miami... ];

现在更好的部分是,我想要一个包含 Bob 的字典(假设所有的名字都是唯一的)。

如果那是一个字典数组,我会这样做

  NSPredicate *pred = [NSPredicate predicateWithFormat:@"(name BEGINSWITH[cd] %@)", @"Bob"];
  NSarray *filteredNames = [self.arrayAll filteredArrayUsingPredicate:pred];

但是因为arrayAll是一个dicts数组,所以这不适用于以下错误:

*** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“无法对不是字符串的内容进行子字符串操作????

有什么线索吗?

【问题讨论】:

    标签: ios cocoa-touch nsarray nsdictionary nspredicate


    【解决方案1】:

    我会这样做......

    NSMutableArray *results = [NSMutableArray array];
    
    [citiesArray enumerateObjectsUsingBlock:^(NSArray *dictArray, NSUInteger idx, BOOL *stop) {
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"(name BEGINSWITH[cd] %@)", @"Bob"];
        NSArray *filteredNames = [self.arrayAll filteredArrayUsingPredicate:pred];
    
        [results addObjectsFromArray:filteredNames];
    }];
    

    您可以像这样添加并发选项...

    [citiesArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(NSArray *dictArray, NSUInteger idx, BOOL *stop) {
        //stuff...
    }];
    

    让它也同时运行。我不知道结果数组将如何处理。试试看吧。

    这将利用所有步骤的快速枚举和并发性。

    【讨论】:

    • 别担心,乐于助人。
    【解决方案2】:

    你为什么不做一个快速枚举? 比如:

    for (NSArray *cityArray in self.arrayAll) {
    
       for (NSDictionary *cityDictionary in cityArray) {
    
        if ([[cityDictionary valueForKey:@"name"] isEqualToString:@"Bob"]) {
          //do something
        }
    
      }
    
    }
    

    【讨论】:

    • 我也在考虑这个,但是对于设备来说不是超级重吗?
    • 没有。这种枚举一直发生在不同的框架中,但同时发生。我建议您在不同的线程上执行此操作,如果您需要从中更新 UI,只需调用主线程即可。
    猜你喜欢
    • 1970-01-01
    • 2015-03-29
    • 2019-09-12
    • 1970-01-01
    • 2016-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    相关资源
    最近更新 更多