我想在swift 3中更新核心数据对象。经过一些谷歌搜索后,我没有发现任何关于swift 3的内容。 所以我的问题是:如何在swift 3中更新核心数据对象?
答案 0 :(得分:21)
使用带谓词的提取请求获取现有值。在谓词中使用唯一值。获取对象后,使用新值更新对象并保存上下文。
let empId = "001"
let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "EmpDetails")
let predicate = NSPredicate(format: "empId = '\(empId)'")
fetchRequest.predicate = predicate
do {
let result = try persistentContainer.viewContext.fetch(fetchRequest)
if let objectToUpdate = result.first as? NSManagedObject {
objectToUpdate.setValue("newName", forKey: "name")
objectToUpdate.setValue("newDepartment", forKey: "department")
objectToUpdate.setValue("001", forKey: "empID")
do {
try persistentContainer.viewContext.save()
} catch {
print(error)
}
}
} catch {
print(error)
}
答案 1 :(得分:0)
在变量“ id”(在Core数据模型中创建的唯一变量)和要更新值的所有变量中传递唯一ID:
func context() -> NSManagedObjectContext {
let context=(UIApplication.shared.delegate as!AppDelegate).persistentContainer.viewContext
return context
}
func save() {
(UIApplication.shared.delegate as! AppDelegate).saveContext()
}
func UpdateCartByTestId(id:Int64,name:String) {
let fetchRequest =
NSFetchRequest<NSManagedObject>(entityName: "Update")
fetchRequest.returnsObjectsAsFaults = false
fetchRequest.predicate = NSPredicate(format:"id == %d",id)
let result = try? context().fetch(fetchRequest)
if result?.count == 1 {
let dic = result![0]
dic.setValue(id, forKey: "id")
dic.setValue(name, forKey: "name")
save()
}
}