swiftnspredicate

Multiple NSPredicates for NSFetchRequest in Swift?


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!


Solution

  • 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"