3

为什么会崩溃?

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

3 回答 3

7

您正在调用entityForName:inManagedObjectContext:which 返回一个NSEntityDescription. 这将是实体的定义,就像您在构建模型时在 GUI 中描述它的方式一样。

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

于 2012-09-07T20:24:33.297 回答
1

你这样做是错的。这是来自开发网站

编辑实体描述:

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.

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

于 2012-09-07T19:12:45.173 回答
0

试试这个:

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

在这里找到如何编辑从 iOS5 中的妈妈加载的 NSManagedObjectModel

于 2012-09-07T18:45:12.963 回答