I am trying to do the right thing by passing my MOC into the view controllers that need them. I am using a third party lib to create a Side/Navigation menu and I am having trouble figuring out how to get my MOC through from the SideController into my ViewControllers that do the work.
Started with this (easy part) Step 1:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
LoginViewController *rootView = (LoginViewController *) self.window.rootViewController;
rootView.managedObjectContext = self.managedObjectContext;
}
Then after my user logins in I pass it one to the third part controller (still ok here) Step 2:
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
NSString *segueIdentifier = [segue identifier];
if ([segueIdentifier isEqualToString:@"LoginSegue"]) {
TheRootViewController *rootViewController = [segue destinationViewController];
rootViewController.managedObjectContext = self.managedObjectContext;
}
}
Here is the third part code Step 3:
- (void)awakeFromNib
{
...
MyNavigationController *navigationController = [self.storyboard instantiateViewControllerWithIdentifier:@"contentViewController"];
navigationController.managedObjectContext = _managedObjectContext;
self.contentViewController = navigationController;
...
}
My problem is this, the code in Step 3 (awakeFromNib) gets called before my segue in Step 2 has a chance to set the MOC on RootViewController.
Basically all examples I can find are using storyboards all the way through, but I have somewhat of a hybrid since my third party app uses code. How do I get the MOC to TheRootController before the awakeFromNib gets called? Is that even possible. Is there another way?
I am really early on in the project and would like to not start stuffing things in the AppDelegate but struggling with figuring out how to do the right thing in the midst of a third party app.
If you'd like to stick to passing the MOC from controller to controller, you could simply move your awakeFromNib code that references the MOC into viewDidLoad. viewDidLoad will be called after the prepareForSegue function completes.
I'd also like to add that is indeed a bad idea to stuff the MOC into the AppDelegate. But as @spassas suggests, it might be a good idea to use a singleton object that manages the MOC for you. I regularly use one in my projects. You can see an example in this gist: https://gist.github.com/grantamos/1156fe4d2461dafd9d67