- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
这两种方法有什么区别?
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/
似乎有两种方法可以在不阻塞主线程 UI 的情况下在 CoreData 中执行异步读取。 newBackgroundContext + NSFetchRequest 来源:https://www.adv
我正在熟悉 NSPersistentContainer .我想知道使用 newBackgroundContext 生成私有(private)上下文的实例是否更好。每次我需要在后台插入/获取一些实体或创
stack overflow 中已经有类似的问题,但它对我不起作用。 在我的应用程序中有一个用例,我必须观察数据库更改才能执行某些操作。为了接收更新,我订阅了 NSManagedObjectConte
这两种方法有什么区别? container.performBackgroundTask { (context) in // ... do some task on the context
我有一个NSManagedObject NewOrder,它只存储NSManagedObjectID以便于上下文。当我需要访问它时,我位于主上下文中,或者位于BG线程上persistentContai
在我的应用程序中,我有一个 NSFetchedResultsController 用于在 UITableView 中加载核心数据对象。与此 FRC 关联的提取请求使用可用于 NSPersistentC
我是一名优秀的程序员,十分优秀!