RESideMenu icon indicating copy to clipboard operation
RESideMenu copied to clipboard

Passing managedObjectContext to other controllers

Open newmanw opened this issue 10 years ago • 2 comments

I have followed your storyboard example and it worked great. I am running into one problem though. I cam coming from an app in which I followed apples pattern of passing my managedObjectContext to the view controllers that need it. I can get my MOC into the content view controller:

MyNavigationController *navigationController = [self.storyboard instantiateViewControllerWithIdentifier:@"contentViewController"];
navigationController.managedObjectContext = _managedObjectContext;
self.contentViewController = navigationController;

From there though I am not sure how to get it through to my other view controllers. I tired implementing prepareForSegue in 'MyNavigationController' but that never gets called to I cannot 'inject the MOC into my other view controllers.

Have you done this. Any advice?

This really relates to passing anything down from one controller to another, it just so happens that a MOC is very common.

newmanw avatar Jun 28 '14 03:06 newmanw

The first concrete problem I am trying to work around:

RootViewController awakeFromNib gets called before my segue can set the MOC. ie. in my LoginViewController I do:

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    NSString *segueIdentifier = [segue identifier];
    if ([segueIdentifier isEqualToString:@"LoginSegue"]) {
        RootViewController *rootViewController = [segue destinationViewController];
        rootViewController.managedObjectContext = self.managedObjectContext;
    }
}

But awake from nib is called first, which is where I try and grab the MOC from the rootViewController its null at that point cause its the prepare for segue that sets it, which gets called right after awakeFromNib, ie (in RootViewController):

 - (void)awakeFromNib
 {
   MyNavigationController *navigationController = [self.storyboard instantiateViewControllerWithIdentifier:@"contentViewController"];
   navigationController.managedObjectContext = _managedObjectContext;
   self.contentViewController = navigationController;
   ...

newmanw avatar Jun 28 '14 03:06 newmanw

AppDelegate code:

mainViewController *mainController = ((mainViewController*)self.window.rootViewController);
NSLog(@"delegateMOC: %@",self.managedObjectContext);
mainController.managedObjectContext = self.managedObjectContext;

ActivityCollectionViewController *activityController = (ActivityCollectionViewController *)mainController.contentViewController;

activityController.managedObjectContext = self.managedObjectContext;

leftMenuController *leftMenu = (leftMenuController *)mainController.leftMenuViewController;

leftMenu.managedObjectContext = self.managedObjectContext;    

I hope it will help)

emartinson avatar May 08 '15 09:05 emartinson