请帮助我,我想在NSCompoundPredicate的Swift 2.2 NSPredicate数组中创建一个coredata get函数
public func loadData(entityName: String, filters: [String: String] = [:], dataFault: Bool = true) -> [NSManagedObject] {
var listItems: [NSManagedObject]?
let delegate = UIApplication.sharedApplication().delegate as? AppDelegate
if let context = delegate?.managedObjectContext {
let fetchRequist = NSFetchRequest(entityName: entityName)
if (filters.count > 0) {
var predicte: [NSPredicate]
for (key, value) in filters {
let p1:NSPredicate = NSPredicate(format: "%K == %@", key, value as NSObject)
predicte.appendContentsOf(p1)
}
fetchRequist.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicte)
}
fetchRequist.returnsObjectsAsFaults = dataFault
do{
let results = try context.executeFetchRequest(fetchRequist)
listItems = results as? [NSManagedObject]
}
catch let err {
print(err)
}
}
else{
print("context Error")
}
return listItems!
}
在predicte.appendContentsOf(p1)上显示错误
答案 0 :(得分:1)
在您的代码中,p1
不是CollectionType,因此您需要使用append
,而不是appendContentsOf
:
predicte.append(p1)
此外,您需要适当地初始化predicte
:
var predicte: [NSPredicate] = []