views:

810

answers:

3

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?

+1  A: 

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.

mrueg
I'm not creating the controllers manually. They're being created automatically after putting the UI together through the interface builder for the iphone.
aryeh
A: 

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

[[[UIApplication sharedApplication] delegate] managedObjectContext]

aryeh
+1  A: 

The answers to this question provide several means of accessing the Core Data stack deep within your application. As I indicate in one of the comments, I prefer to use a singleton DatabaseController that can be accessed from wherever, similar to how the NSUserDefaults' standardUserDefaults works.

Brad Larson