jjzjj

ios - 核心数据 : What's the difference between performBackgroundTask and newBackgroundContext()?

coder 2023-09-12 原文

这两种方法有什么区别?

container.performBackgroundTask { (context) in 
    // ... do some task on the context

    // save the context
    do {
        try context.save()
    } catch {
        // handle error
    }
}

let context = persistentContainer.newBackgroundContext()
context.perform {
    // ... do some task on the context

    // save the context
    do {
        try context.save()
    } catch {
        // handle error
    }
}

何时使用第一种方法,何时使用第二种方法?

最佳答案

区别在于并发的处理方式。

使用performBackgroundTask...

container.performBackgroundTask { (context) in 
    // ... do some task on the context
}

容器创建一个新的后台上下文来执行任务。此函数会立即返回,因此如果您在任务完成之前再次调用它,则两个任务可能会同时运行。

使用newBackgroundContext...

let context = persistentContainer.newBackgroundContext()
context.perform {
    // ... do some task on the context
}

您创建一个新上下文并在后台执行一些操作。如果您再次调用 context.perform 在相同的上下文中,新的闭包也会在后台运行。但由于是相同的上下文,第二个要等到第一个结束后才会开始。

归根结底,第一个可以让多个后台上下文同时工作,而第二个可以更轻松地确保只有一个。

第一个选项可以有更多的同步后台任务,这可能很好,但也可能意味着多个调用有冲突的变化。第二个选项序列化后台任务,因为它们不会同时运行,所以它们不会相互冲突。哪个更好取决于您在闭包中做什么。

关于ios - 核心数据 : What's the difference between performBackgroundTask and newBackgroundContext()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53633366/

有关ios - 核心数据 : What's the difference between performBackgroundTask and newBackgroundContext()?的更多相关文章

随机推荐