2011-12-14 28 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上下文之前继续实际上得到保存。

相关问题