我正在尝试以编程方式快速为一个已经存在的实体创建一个新的属性。
这是我的代码:
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/