在swift 3中创建复杂的NSCompoundPredicate

时间:2017-09-24 09:02:13

标签: swift core-data nspredicate nscompoundpredicate

我想在swift 3中创建一个复杂的 NSCompoundPredicate ,但是,我不知道如何做到这一点。

假设我有5个谓词(p1,p2,p3,p4,p5)。我想在以下条件下实施:

compound1 = (p1 AND p2 AND p3) // NSCompoundPredicate(type: .and, 
                              //subpredicates: predicates)
compound2 = (p4 AND p5) // NSCompoundPredicate(type: .and, 
                       //subpredicates: predicates)
compound3 = (compound1 OR compound2) // problem is here

fetchRequest.predicate = compound3

NSCompoundPredicate 因为它的第二个参数得到了它不想要的NSPredicates数组。什么是最好的解决方案?

1 个答案:

答案 0 :(得分:6)

NSCompoundPredicate继承自NSPredicate,因此您 可以在第一步中传递复合谓词创建 作为另一个复合谓词的次级预测:

let compound1 = NSCompoundPredicate(type: .and, subpredicates: [p1, p2, p3])
let compound2 = NSCompoundPredicate(type: .and, subpredicates: [p4, p5])
let compound3 = NSCompoundPredicate(type: .or, subpredicates: [compound1, compound2])

fetchRequest.predicate = compound3