Passing Managed Object Context in iOS 5.x

Passing a Managed Object context to View Controllers is a challenge.  There are more than one way to do it.

  • Referencing in App Delegate
  • SubClass the ViewController
  • Prepare for Segue ( Yes this is interesting and more relevant when you are trying to build you app using latest Storyboard feature

In my current example I m loading the app with a login page which on success redirects to a TabController.

// Pass the managed object context to the root view controller (the login view)
  LoginViewController *rootView = (LoginViewController *)self.window.rootViewController;
rootView.managedObjectContext = self.managedObjectContext;

 This will make available the managed object context to first Navigation View Controller.

In LoginViewController.h we need to pass in prepareForSegue. Here the catch is topViewController as the table view controller is embedded in navigation controller.

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {     
NSString *segueIdentifier = [segue identifier];     
if ([segueIdentifier isEqualToString:@"YourSegueIdentifier"]) 
// This can be defined via Interface Builder     
if([segue.identifier isEqualToString:@"LoginSegue"]){  
// The controll is passed to TabBarViewController
UITabBarController *tabBarViewController = (UITabBarController *) [segue destinationViewController];
ReceiptsListViewController *receiptsListViewController = (ReceiptsListViewController *) [[[tabBarViewController viewControllers] objectAtIndex:5] topViewController];
    receiptsListViewController.managedObjectContext = self.managedObjectContext;


2 thoughts on “Passing Managed Object Context in iOS 5.x

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s