如何使用备用线程的更改来更新其他上下文

时间:2011-12-14 18:19:08

标签: cocoa core-data

我有一个在主线程上使用的mainContext。创建mainContext时,我向NotificationCenter添加一个观察者,以获取NSManagedObjectContextDidSaveNotification通知。

如果创建了新线程并需要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];
}

1 个答案:

答案 0 :(得分:0)

waitUntilDone:NO //should have been YES

我忽略了这一点。我打算等到它完成。否则,保存发生(在线程2上),通知被调度,contextChanged:处理程序被触发,其他上下文被告知合并其线程上的更改(比如线程1),线程2继续在线程1上下文之前实际上是要保存。