由於核心數據需要一個管理的每個線程對象上下文,一個可能的解決方案來跟蹤每線程上下文的全球經理,然後跟蹤保存通知,並傳播到所有線程:
假設:
@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