Search code examples
iosobjective-ccore-datansmanagedobjectcontext

Accessing ManagedObjectContext


I am in the process of integrating Core Data into an app that was not created with a Core Data template. I am having issues with this and there is probably a very simple answer. However, since most tutorials on this subject are geared towards using the template, I am stumped.

I have followed recommendations for creating a simple app with Core Data checked and copying the generated code into my existing app. However, I can't figure out how to access the NSManagedObjectContext outside of the AppDelegate. I have several view controllers and it is in those that I need access to the managed object context.

The generated code that I copied into the app was placed into AppDelegate, as well as a reference to CoreData in the .pch file. Am I missing something? How do I get access to the managed object context?

Thanks! V


Solution

  • There are several ways you can share your object context around your app. Note that you'll need to make sure you don't use the context on different threads; you'll have to add some complications if you want to use Core Data in both the background and foreground threads.

    Which option you use is up to you:

    • I typically move the Core Data objects (persistent store coordinator, managed object model, contexts for foreground and background threads) into a singleton object, so any class that needs it can get the objects without adding much in the way of upward dependencies.
    • You can use dependency injection to pass the context into your view controllers as you create them in your app delegate, and from those view controllers down into other objects that need them.
    • You can expose the Core Data getters in your app delegate's header; then in your classes you can get the app delegate with [[UIApplication sharedApplication] delegate] and get the CD objects directly from the app delegate (I don't like this approach, but it involves the fewest code changes, probably).