Is it possible to 'force' the app to accept a new model version even if it means overwriting the existing one?

戏子无情 提交于 2020-01-04 13:32:46

问题


Firstly, I'm not 100% clued up on Core Data, but I do what I can. So I've implemented Lightweight Migration for when the app is updated, but recently this has failed, i.e. the app crashes after trying to access the local DB. I currently assume that the reason is because of some mix up with the model versions, but even if not so, I think my question is still valid:

Is there a way, when updating/upgrading an app, to ignore the Core Data migration process and force the app to use the latest model version, even if it deletes the local user data?

My plan is that if the migration fails, force the latest version onto the device. That's a better solution than a crashing app


回答1:


The migration happens during the addPersistentStoreWithType call. So if that fails and you want to start with a new empty database, just remove the persistent store file and call addPersistentStoreWithType again:

_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
    [[NSFileManager defaultManager] removeItemAtURL:storeURL error:NULL];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        // Handle fatal error
    }
}

This is also useful during development, because you don't have to delete the app each time you change your model.



来源:https://stackoverflow.com/questions/19900348/is-it-possible-to-force-the-app-to-accept-a-new-model-version-even-if-it-means

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!