如何将模型数组保存到核心数据NSmanagedobject?

时间:2019-05-23 13:13:16

标签: arrays swift core-data

我正在处理每次单独添加到核心数据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)")
        }
    }

这不仅不会删除所需的行,而且实际上会重复复制该行多次,我不知道为什么。

1 个答案:

答案 0 :(得分:1)

您的代码没有意义。方法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()
    }
}