I'd recommend passing the NSManagedObjectContext to the appropriate view controller/s as recommended in the Apple documents.
This involves the following steps:
- prepare your Core Data stack;
- retain a strong reference to the
NSManagedObjectContext prepared in the Core Data stack;
- include an
NSManagedObjectContext public property in your (swift) view controller file;
- set that public property in the view controller from the reference held in the stack.
From the Apple Documentation...
Getting a Managed Object Context
In iOS:
By convention, you get a context from a view controller. You must
implement your application appropriately, though, to follow this
pattern.
When you implement a view controller that integrates with Core Data,
you can add an NSManagedObjectContext property.
When you create a view controller, you pass it the context it should
use. You pass an existing context, or (in a situation where you want
the new controller to manage a discrete set of edits) a new context
that you create for it. It’s typically the responsibility of the
application delegate to create a context to pass to the first view
controller that’s displayed.
A view controller typically shouldn’t retrieve the context from a
global object such as the application delegate—this makes the
application architecture rigid. Neither should a view controller
create a context for its own use (unless it’s a nested context). This
may mean that operations performed using the controller’s context
aren’t registered with other contexts, so different view controllers
will have different perspectives on the data.
Sometimes, though, it’s easier or more appropriate to retrieve the
context from somewhere other than application or the document, or the
view controller. Several objects you might use in a Core Data-based
application keep a reference to a managed object context. A managed
object itself has a reference to its own context, as do the various
controller objects that support Core Data such as array and object
controllers (NSArrayController and NSObjectController in OS X, and
NSFetchedResultsController in iOS).
Retrieving the context from one of these objects has the advantage
that if you re-architect your application, for example to make use of
multiple contexts, your code is likely to remain valid. For example,
if you have a managed object, and you want to create a new managed
object that will be related to it, you can ask original object for its
managed object context and create the new object using that. This will
ensure that the new object you create is in the same context as the
original.