Best Practices for NSManagedObjectContext Dependency Injection

What is deemed today as best practice for NSManagedObjectContext injection, namely for programmatic controllers?


This past WWDC's Core Data Best Practices talk showed off a brief example where the main-thread context was passed into the view controller as a constructor parameter. However, my view controller is also going to perform a network fetch & upsert of the recieved payload into the Core Data store, so I'm going to need a background context. Do I:


1. Inject both a main thread context and a background thread context into the view controller?

2. Inject just the main thread context and have the VC create a background context that's a child of it?

3. Assume the main thread context has automaticallyMergesChangesFromParent enabled and have the VC create a background context that refers directly to the main thread context's store coordinator?

4. Inject the NSPersistentContainer?

I would make a subclass of NSPersistentContainer and add a method to it for the network upate, inject that into the view controller an call the method. Since it is now in the container it will out-live the view controller, and you can also prevent the method being called twice, or queue them up.

Best Practices for NSManagedObjectContext Dependency Injection
 
 
Q