0
我有一個mainContext用於主線程。在創建mainContext時,我將觀察者添加到NSManagedObjectContextDidSaveNotification通知的NotificationCenter中。如何使用來自備用線程的更改更新其他上下文
如果一個新的線程被創建並且需要一個NSManagedObjectContext,我在這個新線程上創建了上下文,併爲它存儲了一些信息。我保存對新線程上下文的更改。
我的通知處理程序被調用併合並其線程上所有上下文的更改。我有一個影響每個上下文的合併策略,我正在合適的線程上進行更改。
我仍然隨機獲得「樂觀鎖定失敗」。有什麼我失蹤?
- (void)contextChanged:(NSNotification *)notif
{
//gets called from the thread(where the context was) that made the changes
//iterate over all contexts and mergeChanges on their thread
NSLog(@"NotifContext %@ %p", [notif object], [NSThread currentThread]);
//always check the main
if([notif object] != [self mainContext]){
NSLog(@"merge with main %@", [self mainContext]);
[[self mainContext] performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:) withObject:notif waitUntilDone:NO];
}
//check alternate cotexts and merge changes on their threads
NSDictionary *altContexts = [self.altContexts copy];
for(NSString *threadAddress in altContexts){
NSDictionary *info = [altContexts objectForKey:threadAddress];
NSManagedObjectContext *context = [info objectForKey:@"context"];
if(context != NULL && [notif object] != context){
NSLog(@"merge with %@", context);
NSThread *thread = [info objectForKey:@"thread"];
[context performSelector:@selector(mergeChangesFromContextDidSaveNotification:) onThread:thread withObject:notif waitUntilDone:NO];
}else{
NSLog(@"not with %@", context);
}
}
[altContexts release];
}