Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 998
Jason Avatar asked Nov 15 '22 08:11

Jason


1 Answers

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.

like image 75
Tim Avatar answered Dec 19 '22 12:12

Tim