2
votes

I've released an app with a Core Data sqlite database. In the new version of my app, I've created a new "Model Version" of my xcdatamodel in XCode. In the new version an entity is removed and some new attributes are added to one of the entities.

When updating to the new app version, I'm getting this sql error:

The model used to open the store is incompatible with the one used to create the store

How can I handle this error? All data in the database are downloaded from the web, so maybe the easiest way is to just delete the current sqlite file when this error occurs and start from scratch -- but what do people do when the database contains data that cannot be regenerated?

SOLUTION:

I've created an Mapping Model in Xcode and changed my persistentStoreCoordinator getter to handle an option dictionary to the addPersistentStoreWithType:configuration:URL:options:error: method with the key NSMigratePersistentStoresAutomaticallyOption.

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (__persistentStoreCoordinator != nil)
    {
        return __persistentStoreCoordinator;
    }

    NSURL *cacheURL = [[[NSFileManager defaultManager] URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask] lastObject];
    NSURL *storeURL = [cacheURL URLByAppendingPathComponent:@"MyDatabase.sqlite"];
    NSString *storePath = [storeURL path];

    NSError *error = nil;
    NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error])
    {        
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }    

    return __persistentStoreCoordinator;
}
1

1 Answers

3
votes

The problem you're having is that you have to migrate the data from the old core data files to the new core data files. This is why you're getting the "incompatible" error in your question. If you change your core data model then you will need to supply the old version and the new version and tell the system how to move the data from the old version to the new version.

To do this you need to use core data versioning (using bundles) and create migration schemes. Its a complicated process that is probably to difficult to explain in this answer. Normally you can create a new version of your core data files and it will migrate the data automatically, but there are times when you could have issues.

Best thing to do would be to look up core data versioning in google. A quick search turns up this quite comprehensive tutorial http://www.timisted.net/blog/archive/core-data-migration/. It looks pretty good.