开发者

Core Data Migration: 'Can't merge models with two different entities...'

I added new version to Core Data model. I added new attribute to one entity (Seriese)

But it raise exception

 *** Terminating app due to uncaught excep开发者_如何学运维tion 'NSInvalidArgumentException', reason: 'Can't merge models with two different entities named 'Seriese'' 

I use the following code:

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    if (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
    }

    NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationPrivateDocumentsDirectory] stringByAppendingPathComponent: @"CoreDataTutorialPart4.sqlite"]];

    NSError *error = nil;
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:  
                                            [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,  
                                            [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];


    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) {

        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }    

    return persistentStoreCoordinator;
}

Any suggestions to solve this error? I don't want to lose the saved data


The issue more than likely comes from how you load you managed object model. The default way is to merge the models in the bundle, however in this case you actually have two models with the same entities (v1 and v2)... it is explained nicely here....Migration Issues


Core Data does not understand that the entity Seriese in both models is intended to be the same entity and that it should translate the attributes of the old Seriese to the new Seriese. Instead, it thinks the new Seriese should be treated as an entirely new entity.

This is usually caused by trying to make changes to the new version that automatic migration cannot handle. Automatic migration can handle changes to attribute names, adding an attribute or other changes that don't affect anything beyond a single entity. Once you begin to change relationships and/or add new entities, you have to do a manual migration.

You can call

+[NSMappingModel inferredMappingModelForSourceModel:destinationModel:error:] 

... to test if an automatic migration is possible. If it returns nil and/or and error, then you can't.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜