我有一个函数从特定实体中获取满足指定标准的那些对象:
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.
编辑:
问题是它只有replacing the first two items,“%K ==%@”.
所以,我必须创建一个NSCompoundPredicate to create a predicate dynamically.
解决方法
要动态创建谓词(具有可变数量的表达式),请使用NSCompoundPredicate,例如
let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: subPredicates)
其中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 == %@",value) subPredicates.append(subPredicate) } let fetchRequest = NSFetchRequest(entityName: entityName) fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: subPredicates) // ... }