I see how to solve the problem but it bothers me that I don't understand why this doesn't work. I have a UIViewController subclass that uses Core Data, so it needs the NSManagedObjectContext. The controller is loaded from a nib file where it's placed under a navigation controller which is inside a tab controller.
I tried doing this in initWithCoder and viewDidLoad and for some reason it doesn't 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:
* Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an entity named 'LogRecord' in this model.'
Which is what you get when your context is nil or the model can't be loaded (or really lacks the entity).
If I do the exact same thing at the top of my saveLogEntry method (which creates managed objects and saves the context) then it works just fine.
If I do what the Recipes sample application does:
- (void)applicationDidFinishLaunching:(UIApplication *)application {
loggingViewController.managedObjectContext = self.managedObjectContext;
// Standard stuff
[window addSubview:tabBarController.view];
[window makeKeyAndVisible];
}
(loggingViewController is an IBOutlet in the app delegate).
Does anyone know what specifically might be going on here? It seems like it fails if done "too early" but especially with viewDidLoad I'd expect it to work since I think that occurs after addSubview is called.