2011-12-14 27 views
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]; 
} 

回答

0
waitUntilDone:NO //should have been YES 

我忽略了這個。我打算等到它完成。否則,保存發生(在線程2上),調用通知,觸發contextChanged:處理程序,告知其他上下文合併其線程上的更改(如線程1),並且線程2在線程1上下文之前繼續實際上得到保存。

相關問題