ioscore-datauimanageddocument

Core Data crash when adding new Attribute of existing Entity in a new version


I have a Core Data Database in my app using UIManagedDocument, and added a new version on top on an old one.

enter image description here

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 enter image description here

I know this is the line of code that crashed because of the exception breakpoint. enter image description here

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.


Solution

  • 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: enter image description here 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.