NSPredicate具有多个参数和“AND行为” [英] NSPredicate with multiple arguments and "AND behaviour"

查看:609
本文介绍了NSPredicate具有多个参数和“AND行为”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数从特定实体中获取满足指定条件的那些对象:

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]()
     }

}

当我传递一个包含多个aguments(多个属性名称和值)的数组时,它似乎创建了像这样的查询:

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...

我想更改AND的这些OR。

I would like to change these ORs for ANDs.

编辑:

问题在于它只是更换带有%K ==%@的前两项

所以,我必须创建一个 NSCompoundPredicate动态创建谓词

So, I have to create a NSCompoundPredicate to create a predicate dynamically.

推荐答案

创建谓词(具有可变数量的表达式)dyn通常,使用 NSCompoundPredicate ,例如

To create a predicate (with a variable number of expressions) dynamically, use NSCompoundPredicate, e.g.

let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: subPredicates)

其中 subPredicates [NSPredicate] 数组,每个子预测
都是从循环中提供的参数创建的,其中

where subPredicates is a [NSPredicate] array, and each subpredicate is created from the provided arguments in a loop with

NSPredicate(format: "%K == %@", key, value)

像这样(未经测试):

func fetchWithPredicate(entityName: String, argumentArray: [NSObject])  -> [NSManagedObject]  {

    var subPredicates : [NSPredicate] = []
    for i in 0.stride(to: argumentArray.count, by: 2) {
        let key = argumentArray[i]
        let value = argumentArray[i+1]
        let subPredicate = NSPredicate(format: "%K == %@", key, value)
        subPredicates.append(subPredicate)
    }

    let fetchRequest = NSFetchRequest(entityName: entityName)
    fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: subPredicates)

    // ...
}

这篇关于NSPredicate具有多个参数和“AND行为”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆