![](/img/trans.png)
[英]Updating an entity record instead of creating a new record with CoreData using Swift
[英]Swift crashes when creating a new CoreData Attribute to an existing entity
我正在嘗試以編程方式快速為現有實體創建新屬性 。
這是我的代碼:
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!]
應用程序始終因以下錯誤而崩潰:
由於未捕獲的異常“ NSInternalInconsistencyException”而終止應用程序,原因:“無法修改不可變模型。”
我怎樣才能解決這個問題?
模型在運行時不可編輯。 請參閱文檔 ,以Editing Models Programmatically
段落。 您只能復制它並進行更改。
您只能在使用數據模型讀取或存儲數據之前對其進行更改。 初次加載時它是可變的,但是一旦將其用於模型編輯以外的其他操作,它就變得不可變。
像這樣更改模型通常不是一個好主意。 但是,如果出於某種原因有必要,則必須在使用模型加載或保存任何數據之前執行此操作。
我實際上並沒有嘗試過,但是如何將模型從常量更改為變量(即var而不是let)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.