Dan
Dan

Reputation: 1447

Coredata save sqlite to Dropbox - Restore issue - Sqlite file not reloaded until app reboots

I have an iPad application that uses Core Data.

I'm trying to use Dropbox syncing of the sqlite file to give my users another way to backup.

Backing up and restoring from dropbox is no issue; however, once restored the application has to be reset for the data to be shown.

I assume this is because the persistent store is still using the old file.

How do I force close the old model and get it re-opened?

I have tried the following with no luck:

 NSPersistentStore* store = [[_persistentStoreCoordinator persistentStores] lastObject];
[_persistentStoreCoordinator removePersistentStore:store error:nil];
[__managedObjectModel release];
__managedObjectModel = nil;
[_persistentStoreCoordinator release];
_persistentStoreCoordinator = nil;
[self persistentStoreCoordinator];
[self managedObjectContext];
[self managedObjectModel];

Upvotes: 4

Views: 584

Answers (2)

charles
charles

Reputation: 11812

In my case, I found something even simpler, that does not require to create a new store, and simply uses the existing one, but makes Core Data think the content has changed because it moved:

NSPersistentStore* store = [[_persistentStoreCoordinator persistentStores] lastObject];
[_persistentStoreCoordinator setURL:store.URL forPersistentStore:store];

You should of course make that this is done while the MOC is locked. AFAICT, the above will implicitely reset the MOC, though you might as well also do it manually as in the solution you proposed.

Upvotes: 0

Dan
Dan

Reputation: 1447

In the end, I went with the following, which reloads the persistent store:

NSError *error;
// retrieve the store URL
NSURL * storeURL = [[__managedObjectContext persistentStoreCoordinator] URLForPersistentStore:[[[__managedObjectContext persistentStoreCoordinator] persistentStores] lastObject]];
// lock the current context
[__managedObjectContext lock];
[__managedObjectContext reset];//to drop pending changes
//delete the store from the current managedObjectContext
if ([[__managedObjectContext persistentStoreCoordinator] removePersistentStore:[[[__managedObjectContext persistentStoreCoordinator] persistentStores] lastObject] error:&error])
{

    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                             [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
    [[__managedObjectContext persistentStoreCoordinator] addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error];//recreates the persistent store
}

dispatch_async(dispatch_get_main_queue(), ^{
    self.ready = YES;
    [[NSNotificationCenter defaultCenter]postNotificationName:kModelDidChange object:nil];
});

[__managedObjectContext unlock];

Upvotes: 2

Related Questions