【问题标题】:Core Data Performing a fetch in performBlock on a background thread核心数据在后台线程的 performBlock 中执行提取
【发布时间】:2017-10-31 12:23:02
【问题描述】:

当我尝试在后台上下文中执行提取时,它会说: [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 助手只是创建一个获取请求,一个 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)")
        }
    }

任何帮助将不胜感激

【问题讨论】:

    标签: ios objective-c core-data magicalrecord


    【解决方案1】:

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

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

    【讨论】:

    • 你可能是对的。我最终使用了一个没有 FRC 的 fetch 请求,并且效果很好。
    猜你喜欢
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 2014-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多