I've used the following code to pass a context to a ViewController in the pass without issue but for some reason it is behaving differently for this project.
- User performs an action
I load the ViewController like so:
ProjectListViewController *projectListViewController = [[ProjectListViewController alloc] init]; projectListViewController.context = [self context]; [self.view addSubview:[projectListViewController view]];
In the viewDidLoad method I have the following:
if (_context != nil) { NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Project" inManagedObjectContext:_context]; [fetchRequest setEntity:entity]; NSError *error; self.projects = [_context executeFetchRequest:fetchRequest error:&error]; }
It turns out _context is nil.
Did a debug, this is what I found.
The ViewDidLoad method is run before it even gets to the line [self.view addSubview:[projectListViewController view]]; therefore the context is not set.
But if I remove the init from the view declaration then the projectListViewController.context = [self context]; gets run and so the context is not nil.
Am I incorrect to think that the ViewDidLoad should not run before the addSubview is called?
Is there a better way to pass the context to the ViewController?