Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access the managedObjectContext from a controller deep in the UI?

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

I have a CoreData Window-Based App for the iPhone. The rootController is a UITabBarController. The first tab view has a UINavigationController attached to it with a table in it's main view.

When the App starts the objectContext is set up, which makes sense to have the App do that once. But now I have the managedObjectContext in the main Controller but I want to get that passed down to the Controller of the View inside the navcontroller, inside the first item in the TabBarController's tab list. How do I do this?

Would naming the one of the fields in the UI Inspector Tool allow me to do something like:

tabcontroller.navcontroller.manageObjectContext = self.managedObjectContext;

Would this only work if the controller was instantiated and 'live'. (Do the controllers not get instantiated until they are needed?) What if this was in a view that was for the most part hidden?

Anyway this is probably a simple thing I'm just not understanding things properly yet.

What is the general right way to share the manageObjectContext that is created and setup in the rootController to the many sub-controllers in the app?

like image 791
aryeh Avatar asked Jan 24 '23 05:01

aryeh


2 Answers

I'm guessing this is the preferred method assuming the core-data initialization is done in the AppDelegate:

[[[UIApplication sharedApplication] delegate] managedObjectContext]

like image 175
aryeh Avatar answered Mar 29 '23 23:03

aryeh


I usually give controllers a - (id)initWithManagedObjectContext:(NSManagedObjectContext *)context init method and a corresponding variable.

If a controller creates another controller in turn, it will, if needed, pass the NSManagedObjectContext to that controller in the same manner.


If you don't want to create an extra init method, just give the controllers a property for the NSManagedObjectContext and set that property directly after creating them.

I usually try to limit the number of controllers that directly deal with and "know about" Core Data though.

like image 41
mrueg Avatar answered Mar 29 '23 23:03

mrueg