I was looking at the Pro Core Data examples and I was wondering what a good way to pass around the ManagedObjectContext is. In the examples in the book, I see the author initialize the ManagedObjectContext in the AppDelegate, then he does this in MasterViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(@"League Manager", @"League Manager");
id delegate = [[UIApplication sharedApplication] delegate];
self.managedObjectContext = [delegate managedObjectContext];
}
return self;
}
Then when a new ViewController is pushed on the stack from a table row selection, this is done:
NSManagedObject *team = [[self fetchedResultsController] objectAtIndexPath:indexPath];
TeamViewController *teamViewController = [[TeamViewController alloc] initWithMasterController:self team:team];
[self presentModalViewController:teamViewController animated:YES];
Using StoryBoards, I don’t see that type of init method anymore. I see the prepareForSegue is mainly used and I see in the Beginning iOS 5 Development book, the author would do something like this:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
UIViewController *destination = ((UINavigationController *)segue.destinationViewController).topViewController;
if ([destination respondsToSelector:@selector(setDelegate:)]) {
[destination setValue:self forKey:@"delegate"];
}
I can’t figure out a good way to keep my classes decoupled and have a reference to the managedObjectContext in my viewControllers. Do I have a managedObjectContext that I just set on all my view controllers that need to see it? Do I do what the author in the first example did and keep a reference to the MasterViewController that has the reference and pass that around to my different ViewControllers? I’m not sure what is “best practices” for something like this. Thanks!
prepareForSegue:sender:is indeed the preferred way to pass data from one view controller to another when using storyboards. The example prepareForSegue code you posted is exactly how you’d do it. I have exactly this code in one of my apps:The Storyboard session from last year’s WWDC is good watching, if you haven’t seen it.