Ox Smith
Ox Smith

Reputation: 509

How to pass NSManagedObjectContext to ViewController embedded in NavigationController & tabBarController

I am having a problem setting up an NSManagedObjectContext to one of my view controllers - LibraryTrackTimeViewController. I am attaching a screenshot (i hope that is not against the rules here) to make it clearer:

https://i.sstatic.net/d6ixp.jpg

As you can see - it is embedded in a NavigationController as well as a tabBarContoller. I am setting up the NSManagedObjectContext for the other viewControllers in appDelegate:

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;

UINavigationController *navigationController = (UINavigationController *)[[tabBarController viewControllers] objectAtIndex:0];

TagLibraryViewController *tagLibraryViewController = (TagLibraryViewController *)[[navigationController viewControllers] objectAtIndex:0];
tagLibraryViewController.managedObjectContext = self.managedObjectContext;

navigationController = (UINavigationController *)[[tabBarController viewControllers] objectAtIndex:1];

LibrariesViewController *librariesViewController = (LibrariesViewController *)[[navigationController viewControllers] objectAtIndex:0];
librariesViewController.managedObjectContext = self.managedObjectContext;

MapViewController *mapViewController = (MapViewController *)[[tabBarController viewControllers] objectAtIndex:2];
mapViewController.managedObjectContext = self.managedObjectContext;

return YES;

}

The other view controllers it is easy to pass the managedObjectContext - but I am having trouble wrapping my ahead around how I can send it to my LibraryTrackTimeViewController because it is embedded.. Any help or advice you can give me- that would be awesome! Is there a better way of sending the objectContexts to my view controllers?

Upvotes: 1

Views: 858

Answers (1)

Mundi
Mundi

Reputation: 80273

If you find it too complicated you can expose the context from the app delegate

// AppDelegate.h
@property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;

and then get it directly from the delegate:

#include "AppDelegate.h"

AppDelegate *delegate = (AppDelegate*)
             [[UIApplication sharedApplication] delegate];
self.managedObjectContext = delegate.managedObjectContext;

This is not a recommendation - I would also recommend that you pass the context to the controllers. But it is a perfectly valid design pattern, so you can use it if you find it easier.

Upvotes: 2

Related Questions