I have a function which fetches those objects from a particular entity that fulfill a specified criterion:
func fetchWithPredicate(entityName: String, argumentArray: [AnyObject]) -> [NSManagedObject] {
let fetchRequest = NSFetchRequest(entityName: entityName)
fetchRequest.predicate = NSPredicate(format: "%K == %@", argumentArray: argumentArray)
do {
return try self.managedContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]
} catch {
let fetchError = error as NSError
print(fetchError)
return [NSManagedObject]()
}
}
When I pass an array with multiple aguments (multiple attribute names and values) it seems that creates a query like this:
attributeName1 = value1 OR attributeName2 = value2 OR attributeName3 = value3 OR...
I would like to change these ORs for ANDs.
EDIT:
The problem was that it was only replacing the first two items with "%K == %@".
So, I have to create a NSCompoundPredicate to create a predicate dynamically.
Swift 3
I found easiest way.
var predicate = NSPredicate(format: "key1 = %@ AND key2 = %@", value1, value2)
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