Swift中NSFetchRequest的多个NSPredicates?

时间:2016-02-08 08:45:39

标签: swift nspredicate

目前,我有一个简单的NSFetchRequest和一个关联的NSPredicate。但是,我希望有一种方法可以追加多个谓词。我在Objective C中看到了一些例子,但没有看到Swift的例子。

你能定义一个NSPredicate列表,或者以某种方式将多个NSPredicate对象附加到单个NSFetchRequest中吗?

谢谢!

2 个答案:

答案 0 :(得分:42)

您可以使用“NSCompoundPredicate”。例如:

    let converstationKeyPredicate = NSPredicate(format: "conversationKey = %@", conversationKey)
    let messageKeyPredicate = NSPredicate(format: "messageKey = %@", messageKey)
    let andPredicate = NSCompoundPredicate(type: NSCompoundPredicateType.AndPredicateType, subpredicates: [converstationKeyPredicate, messageKeyPredicate])
    request.predicate = andPredicate

您可以更改为“AndPredicateType”或“OrPredicateType”

答案 1 :(得分:14)

Swift 4的更新

        let predicateIsNumber = NSPredicate(format: "isStringOrNumber == %@", NSNumber(value: false))
        let predicateIsEnabled = NSPredicate(format: "isEnabled == %@", NSNumber(value: true))
        let andPredicate = NSCompoundPredicate(type: .and, subpredicates: [predicateIsNumber, predicateIsEnabled])

        //check here for the sender of the message
        let fetchRequestSender = NSFetchRequest<NSFetchRequestResult>(entityName: "Keyword")
        fetchRequestSender.predicate = andPredicate

最新Swift版本的变化是:

NSCompoundPredicateType.AndPredicateType replaced by `NSCompoundPredicate.LogicalType.and `

希望它有所帮助!!!

由于