Reputation: 1699
I think I have got something simple wrong here. I am trying to pass the AppDelegate's managedObjectContext to two view controllers. Just for this learning demo, the two ViewControllers are right next to each other. (In my real app, they will be far apart.)
This works:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;
Page1ViewController * page1VC = [[navigationController viewControllers] objectAtIndex:0];
page1VC.managedObjectContext = self.managedObjectContext;
return YES;
}
But when I add the second view controller - objectAtIndex:1, it doesn't:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;
Page1ViewController * page1VC = [[navigationController viewControllers] objectAtIndex:0];
page1VC.managedObjectContext = self.managedObjectContext;
Page2ViewController *page2VC = [[navigationController viewControllers] objectAtIndex:1];
page2VC.managedObjectContext = self.managedObjectContext;
return YES;
}
I get this error:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
I am sure it is close to being correct!? Would be grateful if someone could help. (Btw, I will be using segues to pass managedObjectContext too!)
Upvotes: 1
Views: 1188
Reputation: 18290
A navigation controller will not instantiate all of the view controllers in it's navigation tree when it gets instantiated; but instead only when they are actually about to come on screen. This is a very good thing for memory management.
As you mentioned, you can easily use the prepareForSegue to pass around an MOC. An alternative solution that I have used extensively, is to create a helper class to manage MOC instances for you, which you can use from anywhere. It manages creating custom contexts, and also handles thread safety (never use an MOC on a thread which did not create it! You may run into this issue if you simply pass one MOC around freely)
Upvotes: 2