Replacing Core Data sqlite file while app is running, data does not update

情到浓时终转凉″ 提交于 2020-01-03 13:38:11

问题


I am developing a backup/restore system for my app in which the user can download a backed-up version of the core data store (sqlite file) and replace the currently-used data store with the downloaded file. However, once the user downloads the file and replaces the current data store, none of the data appears to have been updated. But when the app is quit & re-launched, the restored data is available. How can I force my app to reload the core data store's file?

I have tried to access the app delegate from my UIViewController which restores the data, like so, to rebuild the core data stack and propogate it across all view controllers in the navigation stack:

MyAppDelegate *app = [[UIApplication sharedApplication] delegate];
app.managedObjectContext = nil;
app.persistentStoreCoordinator = nil;
app.managedObjectModel = nil;
managedObjectContext = [app managedObjectContext];

NSArray *controllers = [self.navigationController viewControllers];
UIViewController *c;
for (int i = 0; i < [controllers count]; i++) {
    c = [controllers objectAtIndex:i];
    [c setManagedObjectContext:managedObjectContext];
}

But this isn't working, it only throws the following error when I go back to the root view controller: 'The NSManagedObject with ID:0x5d79060 <x-coredata://D8E73D64-C9BA-4CFA-9213-F8BD61749155/MyObject/p2> has been invalidated.'

Does anyone know how to force the app to reload the data and begin working with the new data store file?


回答1:


What I think is tripping you up is the fact that even though you can set all your managed object contexts, store coordinators, and the like to nil, you still have to completely recreate every managed object in use that was based off those objects.

Your best bet is to do what you're doing now, but also find a way to destroy every Core Data object that you've used. Maybe you can pop your various view controllers down to the root and reload that controller from scratch, so that it uses your new Core Data stack? You'll lose a certain amount of user-friendliness (since they'll have to rebuild the view controller stack using the new data you've loaded), but you'll be sure that you've destroyed everything you need to.



来源:https://stackoverflow.com/questions/3374633/replacing-core-data-sqlite-file-while-app-is-running-data-does-not-update

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