【问题标题】:Filter Array of NSDictionaries Based on Objects in Separate Array基于单独数组中的对象过滤 NSDictionaries 数组
【发布时间】:2014-05-15 15:38:12
【问题描述】:

我有一组要过滤的 NSDictionaries。每个字典都包含对应于字符串对象的键“tid”。我想提取所有字典,它们的键“tid”对象不等于单独数组中包含的任何字符串对象。

例如,如果我有一个名为“stringObjects”的数组和一个名为“dictionaries”的字典数组,我想在伪代码中这样做:

for (NSString *string in stringObjects) {
 //if a dictionary in dictionaries contains a string object for it's key @"tid" which is NOT equal to *string, then put it in an array
}

我一直在尝试使用 NSPredicate 来执行此操作,但经过多次尝试后,我无法获得想要的结果。这是我最近尝试的代码(实际上似乎为数组中的每个字典创建了一个包含每个对象的数组,除了键 @"tid" 的对象):

NSSet *savedThreadIds = //set of strings

NSMutableArray *filtered = [NSMutableArray array];

for (NSString *threadId in savedThreadIds) {
      [filtered addObjectsFromArray:[arrayOfDictionaries filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(%K != %@)", @"tid", threadId]]];     
}

感谢任何帮助。

【问题讨论】:

    标签: objective-c nsdictionary nspredicate


    【解决方案1】:

    如果我正确理解您的答案,您正在寻找 NSCompoundPredicate:

    NSMutableArray *predicates = [[NSMutableArray alloc] init];
    for (NSString *string in stringObjects) {
        //Create an array of predicates
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"NOT (tid CONTAINS[cd] %@)",string];
        [predicates addObject:pred];
    }
    //Create a compound predicate from predicate array, with format P1 AND P2 AND P3 etc.
    NSPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:predicates];
    //Filter an your array using compoundPredicate.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-13
      • 2016-11-17
      • 2019-04-29
      • 2020-12-11
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      相关资源
      最近更新 更多