我有一个函数从特定实体中获取满足指定标准的那些对象:
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(多个属性名称和值)的数组时,似乎会创建一个这样的查询:
attributeName1 = value1 OR attributeName2 = value2 OR attributeName3 = value3 OR...
我想为AND更改这些OR.
编辑:
问题是它只用"%K ==%@" 替换了前两个项目.
所以,我必须创建一个NSCompoundPredicate来动态创建谓词.
在您的示例中%K
,%@
格式标记仅由参数数组的前两项替换,其他项将被忽略.
例如,您必须提供要在字符串中替换的所有格式标记
NSPredicate(format: "%K == %@ AND %K == %@", argumentArray:["key1", "value1", "key2", "value2"])
要动态创建谓词(具有可变数量的表达式),请使用NSCompoundPredicate
,例如
let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: subPredicates)
where subPredicates
是一个[NSPredicate]
数组,每个subpredicate都是从循环中提供的参数创建的
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) // ... }