核心数据崩溃不可变对象

use*_*028 2 core-data iphonecoredatarecipes ios

为什么会崩溃?

CategoryOfExpense *newCatEx = (CategoryOfExpense *) [NSEntityDescription entityForName:kCategoryOfExpense inManagedObjectContext:moc];
newCatEx.name = self.nameTextField.text; <- crashes here
newCatEx.icon =  [NSData dataWithData:UIImagePNGRepresentation(self.iconImageView.image)];
Run Code Online (Sandbox Code Playgroud)

错误是:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Can't modify an immutable model.'
Run Code Online (Sandbox Code Playgroud)

Jod*_*ins 6

你正在打电话给entityForName:inManagedObjectContext:谁返回一个NSEntityDescription.这将是实体的定义,就像您在构建模型时在GUI中描述的那样.

我相信你想要的是insertNewObjectForEntityForName:inManagedObjectContext:哪个会创造一个新NSManagedObject的实体.