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

Arrays 如何将模型数组保存到核心数据NSmanagedobject?,arrays,swift,core-data,Arrays,Swift,Core Data,我使用的是每次单独添加到核心数据NSManagedobject中的对象列表,效果很好 我在添加滑动删除功能时面临的问题是,我需要删除core data中当前保存的阵列并保存新的完整阵列,而不是逐个添加。这是我正在使用的代码,它不起作用,我希望有人能指出我做错了什么- func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: Ind

我使用的是每次单独添加到核心数据NSManagedobject中的对象列表,效果很好

我在添加滑动删除功能时面临的问题是,我需要删除core data中当前保存的阵列并保存新的完整阵列,而不是逐个添加。这是我正在使用的代码,它不起作用,我希望有人能指出我做错了什么-


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()
        }
    }


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

您的代码毫无意义。方法
tableView(uu:commit:forRowAt:)
传递当前索引路径,您必须

  • 从数据源阵列中删除该项
  • 删除托管对象上下文中的项
  • 删除该行
  • 保存上下文


删除整个
for
循环,您应该会很好。您可以发送重新排列的代码,以便我更好地理解您吗?删除整个for循环意味着没有引用正在修改的某个数组单元格,因此我无法理解这是如何工作的。您尝试过吗?代码看起来非常错误和毫无意义,您创建了一个对象
customerspersistency
,然后在保存前将
customers
数组中每个元素的属性写入该单个对象。你用它实现了什么?我想我不完全理解NSManagedObject工作原理背后的逻辑。据我所知,它已经是我从核心数据类型创建的一个对象数组,因此我试图实现的是迭代结构模型的所有数组,并将每个对象传递给NSManagedObject,从而从数组中删除删除的对象。在context.delete(item)行我得到:无法将“Customer”类型的值转换为预期的参数类型“NSManagedObject”。我假设数据源数组是“NSManagedObject”子类(这是建议的设计)。否,填充表视图的数据源数组来自我创建的结构模型。我这样做是因为我必须有一个符合Codable协议的模型,并且没有选项对核心数据模型执行类似的更改。因此,我现在被一个需要NSManagedObject的函数困住了,我有自己的模型对象和indexPath,我如何绕过这个问题?
func saveData(){
        do {
            try context.save()
            print("data saved successfully")
        } catch {
            print("error saving context, \(error.localizedDescription)")
        }
    }

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()
    }
}