0
-(void)someBackgroundTask {
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSConfinementConcurrencyType];
[context setPersistentStoreCoordinator:[self coordinator]];
// ...
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self selector:@selector(handleSaveNotification:) name:NSManagedObjectContextDidSaveNotification object:context];
[context save:&error];
// safe?
[notificationCenter removeObserver:self name:NSManagedObjectContextDidSaveNotification object:context];
// ...
}
// meanwhile on the main thread...
-(void)handleSaveNotification:(NSNotification *)notification {
[[self context] mergeChangesFromContextDidSaveNotification:notification];
}
在致電之後很快就可以移除觀察者嗎?CoreData:在save:call後立即刪除'didSave'通知。太快了?
謝謝,湯姆。我通過在每個點上記錄'[thread description]'來檢查,你是對的(當然)。所以我使用你的後者。我已經向蘋果公司提出了一項改進他們的CoreData文檔的建議,至少在這一點上還不清楚。現在到我的問題的其餘部分:我是不是在主線程和這個後臺線程之間建立一個競賽? – QED
「save:」通知將在'save:'回調之前發佈,因此您可以立即刪除觀察者。如果不使用通知,直接調用合併方法仍然會更簡單和更清晰。 –