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];
}