问题
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