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

标签 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)")
        }
    }

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

最佳答案

您的代码毫无意义。 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/

相关文章:

javascript - 获取数组中的第一项和最后一项 - JS

python - 给定置换数组,找到置换

JavaScript:如何将 x 添加到数组 x 次?

swift - 无法解决 swift 4 中的 Null 问题?

swift - 两个标记之间的快速方向

objective-c - 无法在swift中继承NSMangedObject类型的 objective-c 类

javascript - json 数组,数组中返回错误?错误的字符串

swift - 在 Swift 中为自定义类型定义显式转换

swift - 核心数据只保存最后一项

ios - CoreData 类在单元测试中未匹配