Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
669 views
in Technique[技术] by (71.8m points)

ios - NSPredicate with multiple arguments and "AND behaviour"

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In your example the %K and %@ format tokens are replaced only by the first two items of the argument array, the other items are ignored.

You have to provide all format tokens to be replaced in the string for example

NSPredicate(format: "%K == %@ AND %K == %@", argumentArray:["key1", "value1", "key2", "value2"])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...