Currently, I have a simple NSFetchRequest with an associated NSPredicate. However, Im hoping there is a way you can append multiple predicates. I've seen examples in Objective C, but none for Swift.
Can you define a list of NSPredicate's or append multiple NSPredicate objects to a single NSFetchRequest somehow?
Thanks!
You can use "NSCompoundPredicate". For example:
let converstationKeyPredicate = NSPredicate(format: "conversationKey = %@", conversationKey)
let messageKeyPredicate = NSPredicate(format: "messageKey = %@", messageKey)
let andPredicate = NSCompoundPredicate(type: NSCompoundPredicateType.AndPredicateType, subpredicates: [converstationKeyPredicate, messageKeyPredicate])
request.predicate = andPredicate
You can change into "AndPredicateType" or "OrPredicateType"
Update for 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
The change in latest Swift Version is:
`NSCompoundPredicateType.AndPredicateType` replaced by `NSCompoundPredicate.LogicalType.and`
Hope it helps!!!
Thanks
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With