核心数据在后台线程上执行performBlock中的提取

时间:2017-05-30 21:26:55

标签: ios objective-c core-data magicalrecord

当我尝试在后台上下文中执行提取时,它说:  [NSManagedObjectContext Multithreading_Violation_AllThatIsLeftToUsIsHonor ]()

在后台线程上,我想检查对象是否存在然后更新。如果不是,我插入然后更新。出于某种原因,当我尝试执行获取时,xcode一直说我有并发冲突。我不允许在后台环境中执行提取吗?

这是我对上下文的设置:

Persistent store -> Root saving context -> default context (concurrency type main) persistent store -> Root saving context -> background context (concurrency type private)

后台上下文正在尝试执行Block:

    NSManagedObjectContext *backgroundContext = [NSManagedObjectContext MR_context];
    [backgroundContext performBlock:^{
        [Conversation parseConversationAndCalls:objects inContext:backgroundContext];

        ...
    }];

然后parseConversationAndCalls方法调用将执行提取:

+ (void) parseConversationAndCalls:(NSArray*)objects inContext:(NSManagedObjectContext*)localContext {
    ...
    for (NSArray *callData in conversationsCallData) {

        NSNumber *callID = [BPDObject scrubbedInteger:callData[1]];
        Call *call = (Call*) [FetchRequestHelper fetchWithClass:Call.self withID:callID inContext:localContext];  // breakpoint hit here

        if (call == nil) {
            call = [Call insertInManagedObjectContext:localContext];
        }

        [call updateWithValues:callData inContext:localContext];
        call.contact = contact;
    }
}

fetchrequest helper只是创建一个获取请求,一个FRC,然后在performBlock块中执行获取:

    ... //here context is the same as backgroundContext and frc is the fetched results controller
    context.performAndWait {
        do {
            try frc.performFetch()
        } catch {
            fatalError("Failed to perform fetch from FetchedResultsController: \(error)")
        }
    }

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

通常,fetchedResultsController在主线程上运行,因为它用于更新UI。当fetchedResultsController被创建时,它被赋予了一个managedObjectContext,我强烈怀疑它是主要的上下文。因此,当您在后台上下文中调用try frc.performFetch()时,您正在后台线程中访问主线程上下文。

这是我在您分享的代码中看到的内容。您可能还有其他未共享的违规行为。祝你好运追踪他们。