Ios NSPredicate带有多个参数和;和行为”;
我有一个函数,它从满足指定条件的特定实体获取这些对象:Ios NSPredicate带有多个参数和;和行为”;,ios,swift,Ios,Swift,我有一个函数,它从满足指定条件的特定实体获取这些对象: func fetchWithPredicate(entityName: String, argumentArray: [AnyObject]) -> [NSManagedObject] { let fetchRequest = NSFetchRequest(entityName: entityName) fetchRequest.predicate = NSPredicate(format: "%K == %@",
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]()
}
}
当我传递一个包含多个agument(多个属性名称和值)的数组时,似乎会创建如下查询:
attributeName1 = value1 OR attributeName2 = value2 OR attributeName3 = value3 OR...
我想把这些ORs换成ANDs
编辑:
问题是它只与“%K==%@”在一起
因此,我必须创建一个。在您的示例中,
%K
和%@
格式标记只被参数数组的前两项替换,其他项被忽略
例如,您必须在字符串中提供要替换的所有格式标记
NSPredicate(format: "%K == %@ AND %K == %@", argumentArray:["key1", "value1", "key2", "value2"])
要动态创建谓词(具有可变数量的表达式),请使用NSCompoundPredicate
,例如
let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: subPredicates)
其中,subpredicate
是一个[NSPredicate]
数组,每个subpredicate
从循环中提供的参数创建
NSPredicate(format: "%K == %@", key, value)
类似这样(未经测试):
可以使用复合谓词。我会给你Objective-C语法,我会把翻译留给Swift作为练习 如果您的键和值在字典中:
NSDictionary *conds = @{ @"key1": @"value1", @"key2", @"value2" };
NSMutableArray *predicates = [NSMutableArray arrayWithCapacity:conds.allKeys.length];
for (NSString *key in conds.allKeys)
{
[predicates addObject:[NSPredicate predicateWithFormat:@"%K == %@", key, conds[key]]];
}
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:predicates];
斯威夫特3
我找到了最简单的方法
var predicate = NSPredicate(format: "key1 = %@ AND key2 = %@", value1, value2)
的确,它只是替换了前两项。谢谢
var predicate = NSPredicate(format: "key1 = %@ AND key2 = %@", value1, value2)