核心数据崩溃不可变对象

时间:2012-09-07 18:26:44

标签: ios core-data iphonecoredatarecipes

为什么这会崩溃?

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.'

3 个答案:

答案 0 :(得分:6)

您正在呼叫entityForName:inManagedObjectContext:,并返回NSEntityDescription。这就是实体的定义,就像你在构建模型时在GUI中描述它一样。

我相信你想要的是insertNewObjectForEntityForName:inManagedObjectContext:,它将创建一个新的NSManagedObject实体。

答案 1 :(得分: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.

最后提到的例外是你得到的。你需要做的就是进一步。

答案 2 :(得分:0)

试试这个:

  

您可以通过调用-mutableCopy来获取模型的可变副本   NSManagedObjectModel实例。

在此处找到How to edit a NSManagedObjectModel that was loaded from a momd in iOS5