2012-09-07 25 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. 

接近尾声提到的例外是你会得到什么。进一步走向最后是你需要做的。