Search code examples
swiftmultithreadingcore-dataconcurrencybackground-thread

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. Please explain pros and cons of the following fetch methods:

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)

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)

Solution

  • 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.

    In a scenario of creating, you'd better use B), but need to hold the shared background context. 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. but it's not wrong to create one for it.