【问题标题】:Core data async fetch ends up on the main thread核心数据异步获取最终在主线程上
【发布时间】:2021-05-22 17:01:07
【问题描述】:

我正在尝试在我的应用中执行一个异步请求,作为搜索结果更新程序的一部分。

我写了以下代码

    func updateSearchResults(for searchController: UISearchController) {
        guard let text = searchController.searchBar.text else {return}
        let threadingContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
        threadingContext.parent = self.context
        DispatchQueue.global(qos: .userInitiated).async {
            let fetchRequest = MyObject.fetchRequest() as NSFetchRequest<MyObject>
            fetchRequest.predicate = get_predicate(text)
            do {
                let objects = try threadingContext.fetch(fetchRequest).map({ object in
                    return object.objectID
                })
            }
            catch {return}
            DispatchQueue.main.async {
                // Pass results to the search view controller
            }
        }
    } 

但 UI 仍然很慢(即使我没有进行任何显示更新),并且查看时间分析器,我发现我的主线程将 80% 的时间花在以下方面:

所以看来我的请求仍在发送到主线程,我不明白。有人会看到我的错误吗?

(我在上面尝试了几种不同的方法,例如使用threadingContext.perform,但结果相同)

【问题讨论】:

    标签: swift core-data


    【解决方案1】:

    好的,我明白了,我应该阅读Apple的文档,但基本上

    如果上下文的父存储是另一个托管对象上下文,则获取和保存操作由父上下文而不是协调器进行调解。

    这有点微妙,但如果对 fetch 请求而不是 fetch 请求本身执行的操作很慢,我的构造会很有用。

    解决方案是改为设置threadingContext.persistentStoreCoordinator

    【讨论】:

    • 您好,请问您介意发布您的解决方案示例吗?你试过NSAsynchronousFetchRequest吗?因为,我在启用调试标志时使用 NSAsynchronousFetchRequest 时遇到问题 - stackoverflow.com/questions/70538970/… 谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    相关资源
    最近更新 更多