I have a Core Data Database in my app using UIManagedDocument, and added a new version on top on an old one.
The new version works no problem if I'm adding new Entity without altering old Entity. But once I added a new attribute to an existing Entity of the old version. UIManagedDocument crashed at the point initWithFileURL was called. Here's how I created the UIManagedDocument.
UIManagedDocument *document = [[UIManagedDocument alloc] initWithFileURL:databaseURL];
self.databaseDocument = document;
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
self.databaseDocument.persistentStoreOptions = options;
Seems like it crashed at modelByMergingModels called while initWithFileURL
I know this is the line of code that crashed because of the exception breakpoint.
If I delete the newly added attribute, create the NSManagedObject again. The code runs no problem again.
Any hints why is it failing? Any idea will be appreciated.
Accepted answer from this question solved the problem. UIManagedDocument migrate data model
- (NSManagedObjectModel *)managedObjectModel{
NSString *path = [[NSBundle mainBundle] pathForResource:@"Model" ofType:@"momd"];
NSURL *momURL = [NSURL fileURLWithPath:path];
NSManagedObjectModel *managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:momURL];
return managedObjectModel;
}
I don't really know why it has to be told about the file name of the NSManagedObjectModel. But looking into the stack at the point it crashed: It really crashed at the call of UIManagedDocument's initWithFileURL calling of managedObjectModel. And deeper in the stack, it seems to be trying to merge all models that exist in the Bundle. Maybe, I guess that the two versions of the models are being treated as two models to be merged as one, instead of two versions - due to that the two versions appears to be two separate files in the Bundle. While trying to merge, the existence of two Tables w same Name but different attributes are causing conflicts, that's why it crashed.