简体   繁体   English

如何在后台使用 CoreData 获取数据?

[英]How to fetch data with CoreData in the background?

I need to enable my app keep the data for a long time.我需要让我的应用程序长时间保留数据。 When I started reading articles on the topic I faced 3 different approaches and realized I do not see any differences.当我开始阅读有关该主题的文章时,我遇到了 3 种不同的方法,并意识到我没有看到任何差异。 Please explain pros and cons of the following fetch methods:请解释以下 fetch 方法的优缺点:

A)一个)

container.performBackgroundTask { context in
  self.data = try! context.fetch(request)
  DispatchQueue.main.async {
    self.updateUI()
  }
}

B)二)

let context = container.newBackgroundContext()
context.perform {
  self.data = try! context.fetch(request)
  DispatchQueue.main.async {
    self.updateUI()
  }
}

C) C)

let context = container.newBackgroundContext()
let asyncFetchRequest = NSAsynchronousFetchRequest(fetchRequest: request) { result in
  self.data = result.finalResult!.first!.data!
  DispatchQueue.main.async {
    self.updateUI()
  }
}

try! context.execute(asyncFetchRequest)

I think there is no difference for the example you given(only fetch related).我认为您给出的示例没有区别(仅获取相关)。

A) always create a new context, which means it's not safe when multiple running for creating entity or fetch-or-create entity. A)总是创建一个新的上下文,这意味着当多次运行创建实体或获取或创建实体时它是不安全的。

In a scenario of creating, you'd better use B), but need to hold the shared background context.在创建的场景中,最好使用B),但需要持有共享的背景上下文。 when you do 'perform', all jobs running in one queue synchronously.当您执行“执行”时,所有作业都会在一个队列中同步运行。

For C), NSAsynchronousFetchRequest shines when it works with viewContext, you don't have to create a child/background context.对于 C),NSAsynchronousFetchRequest 在与 viewContext 一起使用时会发光,您不必创建子/背景上下文。 but it's not wrong to create one for it.但是为它创建一个并没有错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM