我将 NSManagedObjectContext 从 AppDelegate 传递给 ViewController。然后我从核心数据中获取结果。但是,NSManagedObjectContext 在 ViewDidLoad 方法中始终为零,而在 ViewDidAppear 方法中则不是。
我理解这两种方法之间的区别,但我认为我应该能够从 ViewDidLoad 访问属性,我什至注意到在 Apple 的示例代码中,他们这样做了。
我应该只获取 ViewDidAppear 吗?
- (void)viewDidLoad
{
[super viewDidLoad];
// This code crashings because my because my Context is nil
NSError *error;
if (![[self fetchedResultsController] performFetch:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
exit(-1);
}
}
编辑:我这样通过
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
RootViewController *rootViewController = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:nil];
rootViewController.managedObjectContext = self.managedObjectContext;
UINavigationController *rootNav = [[UINavigationController alloc] initWithRootViewController:rootViewController];
self.tabBarController = [[UITabBarController alloc] init];
self.tabBarController.viewControllers = [NSArray arrayWithObjects:rootNav, nil];
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
}