Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
672 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 Reply

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"])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...