ios - 为现有实体创建新的 CoreData 属性时 Swift 崩溃

标签 ios swift xcode core-data swift3

我正在尝试以编程方式快速为一个已经存在的实体创建一个新的属性
这是我的代码:

    let model = NSManagedObjectModel()
    var properties = Array<NSAttributeDescription>()
    let remoteURLAttribute = NSAttributeDescription()
    remoteURLAttribute.name = "\(foundArray[indexPath.row]) id"
    remoteURLAttribute.attributeType = .stringAttributeType
    remoteURLAttribute.isOptional = false
    remoteURLAttribute.isIndexed = true
    properties.append(remoteURLAttribute)
    entity?.properties = properties
    model.entities = [entity!]

应用程序总是因以下错误而崩溃:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Can't modify an immutable model.'

我该如何解决这个问题?

最佳答案

您只能在使用数据模型读取或存储数据之前更改数据模型。当您第一次加载它时它是可变的,但一旦您将它用于除模型编辑之外的任何其他用途时它就会变得不可变。

像这样改变模型通常不是一个好主意。但如果出于某种原因有必要,您必须在使用模型加载或保存任何数据之前执行此操作。

关于ios - 为现有实体创建新的 CoreData 属性时 Swift 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38716684/

相关文章:

c++ - 如何摆脱警告 : Implicit conversion shortens 64-bit value into a 32-bit value

ios - PHPhotoLibrary.requestAuthorization() 在 iOS 9 上不触发授权提示

ios - 覆盖不同类型的变量属性

ios - swift 索引路径=可选(0)

ios - 如何创建透明的 UITextField?

Swift - 语音识别 - 停止录音

c++ - 第一个参数没有从 'const value_type' 到 'const void *' 的已知转换

ios - 即使使用解决方案集更新 Swift 后也无法使用 withMemoryRebound

ios - 如何在导航栏中的特定位置显示图像?

ios - 在当前区域的 map 上显示图钉