【问题标题】: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 是否不为零?

标签: ios core-data iphonecoredatarecipes


【解决方案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

    【讨论】:

      猜你喜欢
      • 2011-12-19
      • 1970-01-01
      • 1970-01-01
      • 2014-11-09
      • 2023-03-14
      • 2018-09-02
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多