Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 998
ardevd Avatar asked Feb 08 '16 08:02

ardevd


2 Answers

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"

like image 93
Manuel Avatar answered Oct 21 '22 18:10

Manuel


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

like image 41
Harjot Singh Avatar answered Oct 21 '22 19:10

Harjot Singh