1

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.

4

1 回答 1

0

我认为通知是您最好的选择。每个持有对托管对象上下文以及任何托管对象的引用的视图控制器或对象都必须遵守您的自定义重置通知。因为所有这些都将失效。

我只是好奇,您需要删除持久存储文件的原因是什么?是出于隐私或安全原因吗?如果它只是数据的临时性质?

于 2012-06-21T06:55:18.107 回答