Вопрос

Why does this crash?

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

The error is:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Can't modify an immutable model.'
Это было полезно?

Решение

You are calling entityForName:inManagedObjectContext: which returns a NSEntityDescription. That would be the definition of the entity, like how you described it in the GUI when you built the model.

I believe what you want is insertNewObjectForEntityForName:inManagedObjectContext: which will create a new NSManagedObject of the entity.

Другие советы

You're doing it wrong. This is from the dev site:

Editing Entity Descriptions:

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.

The exception mentioned towards the end is what you get. Further towards the end is what you need to do.

Try this:

You can get a mutable copy of the model by calling -mutableCopy on the NSManagedObjectModel instance.

Found here How to edit a NSManagedObjectModel that was loaded from a momd in iOS5

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top