Swift 中 NSFetchRequest 的多个 NSPredicates?

Multiple NSPredicates for NSFetchRequest in Swift?

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

你能定义一个 NSPredicate 列表或将多个 NSPredicate 对象附加到单个 NSFetchRequest 吗?

谢谢!

您可以使用 "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"

更新 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`

希望对您有所帮助!!!

谢谢