由于核心数据需要一个管理的每个线程对象上下文,一个可能的解决方案来跟踪每线程上下文的全球经理,然后跟踪保存通知,并传播到所有线程:
假设:
@property (nonatomic, strong) NSDictionary* threadsDictionary;
这里是如何得到(每线程)管理对象:
- (NSManagedObjectContext *) managedObjectContextForThread {
// Per thread, give one back
NSString* threadName = [NSString stringWithFormat:@"%d",[NSThread currentThread].hash];
NSManagedObjectContext * existingContext = [self.threadsDictionary objectForKey:threadName];
if (existingContext==nil){
existingContext = [[NSManagedObjectContext alloc] init];
[existingContext setPersistentStoreCoordinator: [self persistentStoreCoordinator]];
[self.threadsDictionary setValue:existingContext forKey:threadName];
}
return existingContext;
}
在您的全球经理的init方法的一些点(我用一个单):
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backgroundContextDidSave:) name:NSManagedObjectContextDidSaveNotification object:nil];
然后接收保存通知和传播到所有其他管理上下文对象:
- (void)backgroundContextDidSave:(NSNotification *)notification {
/* Make sure we're on the main thread when updating the main context */
if (![NSThread isMainThread]) {
[self performSelectorOnMainThread:@selector(backgroundContextDidSave:)
withObject:notification
waitUntilDone:NO];
return;
}
/* merge in the changes to the main context */
for (NSManagedObjectContext* context in [self.threadsDictionary allValues]){
[context mergeChangesFromContextDidSaveNotification:notification];
}
}
(为了清晰起见,删除了一些其他方法)
您的意思是说核心数据一次只能访问一个?我对xcode dev很陌生.. – kraitz
不,我的意思是你通过托管对象上下文访问核心数据,你可以在一个应用程序中拥有多个托管对象上下文,并且每个线程都必须有自己的专用托管对象上下文。 :) –
我在应用程序委托中有一个托管对象上下文。如何在新线程上运行的方法中声明新的方法? – kraitz