How to share a ManagedObjectContext when using UITabBarController

前端 未结 9 2308
一整个雨季
一整个雨季 2020-12-23 10:57

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

相关标签:
9条回答
  • 2020-12-23 11:30

    Hello I know this is an old thread, but I'm also having problems finding the best way to handle sharing a MOC between TABS - wish Marcus Zarra's link on the subject was still active. Marcus totally rocks, makes data cool.

    This is my current solution in application didFinishLaunching:

    NSArray *viewControllers = [tabBarController viewControllers];
        NSManagedObjectContext *context = self.managedObjectContext;
        for (id viewController in viewControllers) {
            [viewController setManagedObjectContext:context];
    
    }
    
    0 讨论(0)
  • 2020-12-23 11:35

    I've ran into this same problem, i'll share my solution.

    First you need a reference to the Nav Controller in the Tab Bar in the nib file, make sure you connect it up.

    IBOutlet UINavigationController *navigationController;
    

    Then, get the Controller as recommended in the support docs and send it the managedObjectContext:

    SavedTableViewController *saved = (SavedTableViewController *)[navigationController topViewController];
    saved.managedObjectContext = self.managedObjectContext;
    

    Alex (from another post) is right, "You should generally stay away from getting shared objects from the app delegate. It makes it behave too much like a global variable, and that has a whole mess of problems associated with it."

    0 讨论(0)
  • 2020-12-23 11:36

    If you want to use the dependency injection method to pass the managed object context with a tab bar controller, a more robust solution would be to loop on all the view controllers in applicationDidFinishLaunching:

    for (id vc in tabBarController.viewControllers) {
        [vc setManagedObjectContext:self.managedObjectContext];
    }
    
    0 讨论(0)
提交回复
热议问题