【问题标题】:NSCompoundPredicate constructionNSCompoundPredicate 构造
【发布时间】:2015-09-21 17:46:54
【问题描述】:

假设我在 feedDays 数组中有这个谓词数组:

<__NSArrayM 0x7ff7f3cd1040>(
    feedDay == 1,
    feedDay == 2,
    feedDay == 4
)

我需要用这个 statusPredicates 数组来与它:

<__NSArrayM 0x7ff7f3cd1070>(
    is_neutered == 0 AND other_status == 0,
    is_neutered == 0 AND other_status == 1,
    is_neutered == 0 AND other_status == 2,
    is_neutered == 0 AND other_status == 3,
)

如何将这些组合成一个查询?我假设我必须使用 NSCompoundPredicate 但我不知道如何将它与两个谓词数组结合在一起。

【问题讨论】:

    标签: ios objective-c core-data nsfetchedresultscontroller nscompoundpredicate


    【解决方案1】:

    在我看来,像

    这样的组合谓词
    feedDay == 1 && feedDay == 2 ...
    

    总是错误的

    因此,您可能的意思是将每个谓词与neutered 条件组合,以便两个 条件都为真(and),然后组合这些单独的组,以便 要么 这些都是真的 (or)。

    如果您将数组与and 组合成一个大化合物,则它一定总是错误的。假设neutered 条件始终相同,

    NSPredicate *finalPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:
      @[[NSPredicate predicateWithFormat:@"is_neutered = 0"],
        [NSCompoundPredicate orPredicateWithSubPredicates:feedDays]]];
    

    这很丑,对吧?所以我建议你用feedDay 的可能值创建一个数组并使用简单的

    [NSPredicate predicateWithFormat:
         @"is_neutered = 0 && feedDay in %@", allowedFeedDays]
    

    【讨论】:

    • 很好的深思熟虑的答案。
    【解决方案2】:

    使用此代码 -

    NSMutableArray *allPredicates = [[NSMutableArray alloc] initWithArray:feedDays];
    [allPredicates addObjectsFromArray:statusPredicates];
    
    NSCompoundPredicate *finalPred = [NSCompoundPredicate andPredicateWithSubpredicates:allPredicates];
    

    【讨论】:

    • 这不太正确 - 它产生的数组看起来像 [a,b,c,[d,e,f]] 而不是 [a,b,c,d,e,f] - 您正在将第二个数组完整地添加到第一个数组中,而不是一个一个地添加其成员。
    • 是的 - 现在返回与我的答案相同的结果。尽管实际上现在我运行代码,但您的原始答案还可以-似乎 NSCompoundPredicate 足够聪明,可以处理嵌套的谓词数组-道歉
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多