Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSPredicate with multiple arguments and "AND behaviour"

Tags:

ios

swift

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.

like image 881
angeldev Avatar asked Dec 10 '15 12:12

angeldev


1 Answers

Swift 3

I found easiest way.

var predicate = NSPredicate(format: "key1 = %@ AND key2 = %@", value1, value2)
like image 78
Abdul Hameed Avatar answered Sep 21 '22 13:09

Abdul Hameed