Asynchronous Core Data operations (Chap 4 + Chap 7 + Chap 9)

Hello,
First of all, let me thank the author for the create content!

I am building an app using Core Data. However I want to use some asynchronous requests (fetch and save) to make sure my app UIs are not blocked.

However I am confused with what I am reading within Chap 4, 7 and 9.

  • In Chapter 4, we are using the Asynchronous fetching approach with the use of NSAsynchronousFetchRequest.
  • In Chapter 7, while we are focusing on Unit Testing, the CoreDataStack introduces mainContext and derivedContext. I think this is not really explained what is for, imho. When I am looking at the saveContext functions, it seems the reason for that is to perform some background requests to Core Data. We are saving both the “derived” managed object context and the main managed object context.
  • In Chapter 9, multiple managed object contexts are introduced as a way to perform Core Data requests in background - while we are not using any other context than the main one in Chapter 4.

I would really appreciate some clarification on that subject.

Many thanks, tristan

@tristanouin Thanks very much for your question, and my apologies for the delayed response!

An NSAsynchronousFetchRequest allows you to issue a fetch request to the NSManagedObjectContext and be notified via a closure when the objects have been populated in the context. In other words, whether on the main thread or a background thread, you can continue to work with your NSManagedObjectContext (MOC) while this fetch is executing. So using an NSAsynchronousFetchRequest allows you to work with your MOC, while simultaneously doing a fetch. Thus, you don’t have to wait for the fetch request to complete before continuing your work. The advantage of this is that you don’t need to create a child MOC to do this work on a background thread. This means that you can use a child MOC for more complex, long running tasks that you would want to run on in the background and to use the NSAsynchronousFetchRequests to specifically do fetch requests that your current tasks are not dependent on.

I hope this helps!

All the best!

1 Like

This topic was automatically closed after 166 days. New replies are no longer allowed.