Search code examples
ioscore-datauitabbarcontrollernsmanagedobjectcontext

How to pass NSManagedObjectContext to view controllers when using storyboard (iOS)


I am using a tab bar controller in conjunction with core data. Each of the different tabs needs to have access to the NSManagedObjectContext, however I do not want to use a singleton or just pull them off the app delegate. Is there a way to pass them to the view controller programmatically from the app delegate when the app loads?


Solution

  • If you have a tab based app in a storyboard the rootViewController of the window will be the UITabBarController. From there you can get the viewControllers that make your tabs.

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
        UIViewController *firstVC = tabBarController.viewControllers[0];
        firstVC.managedObjectContext = self.managedObjectContext;
        UIViewController *secondVC = tabBarController.viewControllers[1];
        secondVC.managedObjectContext = self.managedObjectContext;
        // more...
    }