我正在处理一个对象列表,这些对象每次都单独添加到核心数据 NSManagedobject - 工作正常。
我在添加滑动删除功能时遇到的问题,我需要删除核心数据中当前保存的数组并保存新的完整数组,而不是一个一个地添加它们。这是我正在使用的代码,它不起作用,我希望有人能指出我做错了什么 -
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
customers.remove(at: indexPath.row)
let customersPersistancy = CustomerModel(context: context)
for customer in customers {
customersPersistancy.name = customer.name
customersPersistancy.age = Int16(customer.age)
customersPersistancy.surname = customer.surname
customersPersistancy.region = customer.region
customersPersistancy.gender = customer.gender
}
//print(customersPersistancy)
saveData()
tableView.reloadData()
}
}
func saveData(){
do {
try context.save()
print("data saved successfully")
} catch {
print("error saving context, \(error.localizedDescription)")
}
}
这不仅不会删除所需的行,而且实际上会多次复制该行,我不明白为什么。
最佳答案
您的代码毫无意义。 tableView(_:commit:forRowAt:)
方法传递当前索引路径,你必须
- 从数据源数组中移除项
- 删除托管对象上下文中的项目
- 删除行
- 保存上下文
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let item = customers.remove(at: indexPath.row)
context.delete(item)
tableView.deleteRows(at: [indexPath], with: .fade)
saveData()
}
}
关于arrays - 如何将模型数组保存到核心数据 NSmanagedobject?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56276067/