Reputation: 6940
I wonder why my managedObjectContext is nil (in my TableViewController class) when i pass it like that in app delegate:
// Fetch Main Storyboard
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
// Instantiate Root Navigation Controller
UINavigationController *rootNavigationController = (UINavigationController *)[mainStoryboard instantiateViewControllerWithIdentifier:@"rootNavigationController"];
// Configure View Controller
TableViewController *viewController = (TableViewController *)[rootNavigationController topViewController];
if ([viewController isKindOfClass:[TableViewController class]]) {
[viewController setManagedObjectContext:self.managedObjectContext];
NSLog(@"Saved");
}
And in console i could see "Saved" output, but when i log managedObjectContext in my class its nil..
AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication] delegate];
self.managedObjectContext = app.managedObjectContext;
Did solve problem, but i still want to know why previous solution not work?
Upvotes: 0
Views: 47
Reputation: 80265
The reason is that very likely the view controller you are creating in code is actually overwritten with the one sent directly by the storyboard. There is no good reason to create a navigation and view controller from storyboard like this in the app delegate.
So your solution is the correct one and also quite common to have the view controller get its context from a singleton or the app delegate. Keep this pattern and stop worrying about the other problem.
Upvotes: 1