How to share a ManagedObjectContext when using UITabBarController

mvexel picture mvexel · Jan 15, 2010 · Viewed 12.8k times · Source

I have an iPhone application that has a MainWindow.xib holding a UITabBarController, which in turn has a UINavigationController and a custom UIViewController subclass in its ViewControllers array. The root view controller for the UINavigationController and the custom view controller are both loaded from other xib files.

The app uses core data, the stack is initialized in the app delegate (as per the convention).

The app delegate adds the UITabBarController to the window:

- (void)applicationDidFinishLaunching:(UIApplication *)application {        
    // Configure and show the window
    [window addSubview:[tabBarController view]];
    [window makeKeyAndVisible];
}

I realize that I need to propagate a pointer to the ManagedObjectContext created in the app delegate, but I don't know how to proceed (even reading all the good commentary on the topic here and here):

  • Do I propagate the ManagedObjectContext to the UITabBarController and from there on to the individual view controllers and if so, how?
  • Or do I propagate the ManagedObjectContext directly to the root view controller of the UINavigationController and to the custom view controller and how would I do that?

I guess I don't understand well enough how to work with the UITabBarController.

Answer

Marcus S. Zarra picture Marcus S. Zarra · Jan 15, 2010

Ideally you want to pass either the NSManagedObjectContext, NSFetchedResultsController or the relevant NSManagedObject "down" into the UIViewController. This allows the "parent" to control the "child" and determine what the child should have. This creates a more loosely coupled design and allows you to easily re-arrange UIViewController instances as needed. It also makes it easier to reuse a UIViewController.

In a tab view design it is no different. Your AppDelegate passes the NSManagedObjectContext to whoever is responsible for creating the initial UIViewController instances that go into the UITabBarController. In turn that creator passes the relevant information (NSManagedObject, NSFetchedResultsController, and/or NSManagedObject instances) into the UIViewController instances as it is constructing them.