尝试在运行时更改持久性存储时遇到问题。我试图这样做的方法是重新启动整个核心数据堆栈:
- (void)initializeCoreDataForStore:(NSUrl *)storeURL withCompletionBlock:(CoreDataRWCompletionBlock)completionBlock
{
//this code is needed to reset core data stack before re-creating the new one
[_managedObjectContextBackgroundQueue reset];
_managedObjectContextBackgroundQueue = nil;
[_managedObjectContextMainQueue reset];
_managedObjectContextMainQueue = nil;
_managedObjectModel = nil;
_persistentStoreCoordinator = nil;
_persitentStore = nil;
//---------------end reset core data stack ---------------------
//model
self.managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
self.persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];
//main context
self.managedObjectContextMainQueue = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[self.managedObjectContextMainQueue setPersistentStoreCoordinator:self.persistentStoreCoordinator];
//background context
self.managedObjectContextBackgroundQueue = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[self.managedObjectContextBackgroundQueue performBlockAndWait:^{
[self.managedObjectContextBackgroundQueue setPersistentStoreCoordinator:self.persistentStoreCoordinator];
}];
dispatch_queue_t queue = NULL;
queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSError *error = nil;
self.persitentStore = [self.persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error];
dispatch_sync(dispatch_get_main_queue(), ^{
if (completionBlock) {
completionBlock([error localizedDescription], nil);
}
});
});
}
后台上下文的所有工作都是使用performBlock或performBlockAndWait完成的。 问题是,如果我重置并重新启动堆栈,如果在旧的后台上下文中有待处理的“操作”,那些操作没有被取消,并且它们继续执行,那么他们正在尝试使用新实例化的背景上下文,它具有另一个持久存储。 有没有办法从与后台上下文关联的私有队列中取消所有操作(可以在操作队列中取消nsoperations的方式)?