我通常使用managedObjectContext
中的以下代码为根视图设置AppDelegate.h
:
UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;
HomeViewController *controller = (HomeViewController *)navigationController.topViewController;
controller.managedObjectContext = self.managedObjectContext;
但我当前的应用程序在根目录中包含自定义UITabBarController
,后跟UINavigationController
,然后是UIViewController
。如何将managedObjectContext
设置为视图控制器?
答案 0 :(得分:1)
你可以做得非常相似
UITabBarController *tabController = (UITabBarController *)self.window.rootViewController;
// index 0 means left-most tab
UINavigationController *navigationController = (UINavigationController *)tabController.viewControllers[0];
HomeViewController *controller = (HomeViewController *)navigationController.topViewController;
controller.managedObjectContext = self.managedObjectContext;
或者,我更喜欢:
在HomeViewController中执行
#import "AppDelegate.h"
// somewhere (e. g. awakeFromNib, loadView or viewDidLoad)
self.managedObjectContext = ((AppDelegate *) [UIApplication sharedApplication].delegate).managedObjectContext
在你的AppDelegate中使managedObjectContext
成为公共财产。