ios - 在运行时动态创建核心数据实体

标签 ios swift core-data

我需要能够在运行时创建新的核心数据实体。我已经编写了以编程方式创建对象的代码,但是,我无法在运行时添加实体,因为模型是不可变的。

我的问题和这个帖子类似,但是没有满意的答案:How to dyanmic create a new entity (table) via CoreData model?

有关更改核心数据模型的文档说明:

Managed object models are editable until they are used by an object graph manager (a managed object context or a persistent store coordinator). This allows you to create or modify them dynamically. However, once a model is being used, it must not be changed. This is enforced at runtime—when the object manager first fetches data using a model, the whole of that model becomes uneditable. Any attempt to mutate a model or any of its sub-objects after that point causes an exception to be thrown. If you need to modify a model that is in use, create a copy, modify the copy, and then discard the objects with the old model.

但是,我不清楚这到底是什么意思——一旦使用了持久存储协调器,整个核心数据模型就无法更改,或者各个实体的属性等无法更改.

明确地说,我不想更改当前实体的属性,我只是想添加 新实体。必须使用迁移来添加新实体对我来说似乎很奇怪。

有什么想法吗?

谢谢!

最佳答案

文档非常清楚。

  1. 复制模型。
  2. 将您的更改应用到新副本。
  3. 销毁旧的 MOC、Persistent Store Coordinator 以及从中创建的所有对象。
  4. 如有必要,应用迁移。
  5. 使用更新后的模型创建新的核心数据堆栈(MOC、PSC 等)。

迁移可能是一个症结所在,但它应该是可行的。

关于ios - 在运行时动态创建核心数据实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29908435/

相关文章:

javascript - 适用于 iOS/Android 的 jQuery 日期时间选择器

swift - swift 3中饼图上的触摸事件

ios - 替代 Swift 中的单例实现?

ios - 我如何将其转换为 Swift?

ios - MR_SHORTHAND 不起作用

iOS 如何保存类对象的字典?

iphone - iOS 或 MacOS 上的 libspotify : parts of the SPSession fail to be retrieved

android - 2d 手机游戏

iphone - 使 iPhone 应用程序通用

ios - 获取 NSArray 中 NSFetchRequest 的所有结果