When user logs in into my app I download some data from server in a background thread. I have a singleton that sets its managedObjectContext as a child of the main managedobjectcontext.
-(NSManagedObjectContext*) context{
if(!_context){
NSManagedObjectContext *child = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[child setParentContext:[MyAppDelegate delegate].managedObjectContext];
_context = child;
}
return _context;
}
When the users logs out I delete the PersistenceStoreCoordinator sqllite file locking the main managedobjectcontext
-(void)onLogout{
NSError *error = nil;
if ([_persistentStoreCoordinator persistentStores] == nil)
return;
[self.managedObjectContext reset];
[self.managedObjectContext lock];
NSPersistentStore *store = [[self.persistentStoreCoordinator persistentStores] lastObject];
if (![self.persistentStoreCoordinator removePersistentStore:store error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
// Delete file
if ([[NSFileManager defaultManager] fileExistsAtPath:store.URL.path]) {
if (![[NSFileManager defaultManager] removeItemAtPath:store.URL.path error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
_persistentStoreCoordinator = nil;
_persistentStoreCoordinator = [self persistentStoreCoordinator];
[self.managedObjectContext unlock];
self.agendaLoader = nil;
_agendaLoader = self.agendaLoader;
}
If I logout/login in the same simulator session (without stopping the app) the save method in the singleton crashes with following error:
This NSPersistentStoreCoordinator has no persistent stores. It cannot perform a save operation.'
But it works without any problem if i logout/stop the app/restart the app/login.
I tried to reset the child managedobjectcontext on logout without any results..
Are there any best practices to reset all managedobjectcontexts, delete the storecoordinator file, and "reboot" all the core data stack?
Thanks for your help.