I see how to solve the problem, but it bothers me that I do not understand why this does not work. I have a subclass of UIViewController that uses Core Data, so it needs NSManagedObjectContext. The controller is loaded from the nib file, where it is placed under the navigation controller, which is located inside the tab controller.
I tried to do this in initWithCoder and viewDidLoad, and for some reason it does not work:
MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
self.managedObjectContext = [[appDelegate managedObjectContext] retain];
For some reason, managedObjectContext returns nil, and I get this when I try to create a managed object later:
*** Application termination due to the uncaught exception "NSInternalInconsistencyException", reason: "+ entityForName: could not find an object named" LogRecord "in this model. '
This is what you get when your context is zero or the model cannot be loaded (or the object is really missing).
If I do the same at the top of my saveLogEntry method (which creates managed objects and saves context), then it works fine.
If I do what the Recipes sample application does:
- (void)applicationDidFinishLaunching:(UIApplication *)application {
loggingViewController.managedObjectContext = self.managedObjectContext;
[window addSubview:tabBarController.view];
[window makeKeyAndVisible];
}
(loggingViewController is an IBOutlet in the application delegate).
Does anyone know what exactly can happen here? This does not seem to succeed if done "too early", but especially with viewDidLoad, I expect it to work, as I think it happens after addSubview is called.