How to access managedObjectContext from a controller located deep in the user interface?

I'm still a little vague in understanding iPhone / Cocoa in general, so this is probably a simple question.

I have a WindowDate app for CoreData for iPhone. The root controller is a UITabBarController. In the first view of the tab there is a UINavigationController attached to it with the table in the main view.

When the application starts the objectContext, it is configured, which makes sense if the application does this once. But now I have a managedObjectContext in the main controller, but I want to get it passed to the View controller inside the navcontroller, inside the first item in the TabBarController tab list. How to do it?

I would call one of the fields in the tool a UI inspector so that I can do something like:

tabcontroller.navcontroller.manageObjectContext = self.managedObjectContext;

Will this work only if the controller has been created and is "live". (Are the controllers activated until they are needed?) What if it looked like it was mostly hidden?

In any case, this is probably a simple thing, I just do not understand things properly.

What is the general correct way to share the manageObjectContext created and installed in the root controller for many subcontrollers in the application?

+4
source share
3 answers

I assume this is the preferred method, assuming that the initialization of the master data is done in AppDelegate:

[[[UIApplication sharedApplication] delegate] managedObjectContext]

+6
source

I usually provide the controllers with the method - (id)initWithManagedObjectContext:(NSManagedObjectContext *)context init and the corresponding variable.

If the controller alternately creates another controller, it will, if necessary, pass the NSManagedObjectContext this controller in the same way.


If you do not want to create an additional init method, simply give the controllers a property for NSManagedObjectContext and set this property immediately after they are created.

Usually I try to limit the number of controllers that are directly involved and "know about" the main data ".

+2
source

The answer to this question provides several ways to access the Core Data stack within your application. As I point out in one comment, I prefer to use a singleton DatabaseController, which can be accessed anywhere, just like the standard NSUserDefaultsUserDefaults functions.

+1
source

All Articles