【问题标题】:how to save array of model to core data NSmanagedobject?如何将模型数组保存到核心数据 NSmanagedobject?
【发布时间】:2019-10-10 01:52:30
【问题描述】:

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

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

【问题讨论】:

  • 删除整个for 循环就可以了
  • 你能把重新排列的代码发给我吗?
  • 删除整个 for 循环意味着没有对正在修改的数组单元之一的引用,所以我无法理解它是如何工作的。
  • 你试过了吗?代码看起来如此错误和毫无意义,您创建一个对象customersPersistancy,然后在保存之前将customers 数组中每个元素的属性写入该单个对象。你用它实现了什么?
  • 我想我不完全理解这个 NSManagedObject 东西是如何工作的背后的逻辑。据我所知,它已经是我从核心数据类型创建的对象数组,所以我试图实现的是遍历我的结构模型的所有数组并将每个对象传递给 NSManagedObject 一个,因此从数组中删除已删除的对象。

标签: arrays swift core-data


【解决方案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()
    }
}

【讨论】:

  • 在 context.delete(item) 行我得到:
  • 无法将“客户”类型的值转换为预期的参数类型“NSManagedObject”
  • 我假设数据源数组是 'NSManagedObject` 子类(这是推荐的设计)。
  • 不,填充表格视图的数据源数组来自我创建的结构模型。我之所以这样工作,是因为我必须有一个符合 Codable 协议的模型,并且没有选项可以对核心数据模型执行类似的更改。
  • 因此,我现在被一个需要 NSManagedObject 的函数困住了,我有自己的模型对象和 indexPath,我该如何绕过这个问题?
猜你喜欢
  • 1970-01-01
  • 2015-02-26
  • 2016-08-19
  • 1970-01-01
  • 2010-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多