3

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?

3
  • Just add a property managedObjectContext to each view controller and set the value when creating the tab bar controller, e.g. in didFinishLaunchingWithOptions.
    – Martin R
    Aug 4, 2013 at 11:28
  • Thanks - since I am using a storyboard I dont manually create the VC's though. They are already created...
    – user843337
    Aug 4, 2013 at 11:29
  • OK, but if you have an outlet to the tab bar controller then you can access its viewControllers and set the property for each view controller. - (I am not sure if that is better than pulling them from the app delegate ...)
    – Martin R
    Aug 4, 2013 at 11:33

1 Answer 1

2

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...
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.