核心数据崩溃不可变对象
Posted
技术标签:
【中文标题】核心数据崩溃不可变对象【英文标题】:Core data crash immutable object 【发布时间】:2012-09-07 18:26:44 【问题描述】:为什么会崩溃?
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.'
【问题讨论】:
在尝试访问其成员变量之前,您是否检查过 newCatEx 是否不为零? 【参考方案1】:您正在调用entityForName:inManagedObjectContext:
,它返回一个NSEntityDescription
。这就是实体的定义,就像您在构建模型时在 GUI 中描述它的方式一样。
我相信你想要的是insertNewObjectForEntityForName:inManagedObjectContext:
,它将创建一个新的实体NSManagedObject
。
【讨论】:
是的 .. 我就是这么做的【参考方案2】:你做错了。这是来自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.
最后提到的例外就是你得到的。进一步接近最后是你需要做的。
【讨论】:
【参考方案3】:试试这个:
您可以通过调用
-mutableCopy
获取模型的可变副本NSManagedObjectModel
实例。
在这里找到How to edit a NSManagedObjectModel that was loaded from a momd in ios5
【讨论】:
以上是关于核心数据崩溃不可变对象的主要内容,如果未能解决你的问题,请参考以下文章