2012-09-07 27 views
2

爲什麼會崩潰?核心數據崩潰不可變對象

CategoryOfExpense *newCatEx = (CategoryOfExpense *) [NSEntityDescription entityForName:kCategoryOfExpense inManagedObjectContext:moc]; 
newCatEx.name = self.nameTextField.text; <- crashes here 
newCatEx.icon = [NSData dataWithData:UIImagePNGRepresentation(self.iconImageView.image)]; 

的錯誤是:

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

您是否在嘗試訪問其成員變量之前檢查newCatEx是否不爲零? – mark

+0

這不是零.... – user1028028

回答

6

您正在致電entityForName:inManagedObjectContext:,它返回NSEntityDescription。這將是實體的定義,就像您在構建模型時在GUI中描述的那樣。

我相信你想要的是insertNewObjectForEntityForName:inManagedObjectContext:這將創建一個新的實體NSManagedObject

+0

是的..這就是我正在做 – user1028028

1

你就錯了。這是從dev site

編輯實體描述:

Entity descriptions are editable until they are used by an object graph manager. 
This allows you to create or modify them dynamically. 
However, once a description is used (when the managed object model to which it belongs 
is associated with a persistent store coordinator), it must not (indeed cannot) be changed. 
This is enforced at runtime: any attempt to mutate a model or any of its sub-objects 
after the model is associated with a persistent store coordinator 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. 

接近尾聲提到的例外是你會得到什麼。進一步走向最後是你需要做的。