Multiple NSPredicates for NSFetchRequest in Swift?

ardevd picture ardevd · Feb 8, 2016 · Viewed 13.7k times · Source

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!

Answer

Manuel picture Manuel · Feb 8, 2016

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"