我正在尝试从ViewController传递核心数据托管对象上下文(它能够将其从AppDelegate加载到TabBarViewController。

AppDelegate.m
ojit_pre

LoginViewController.m

ojit_pre

When i run it i encounter this error

// Pass the managed object context to the root view controller (the login view)
LoginViewController *rootViewController = (LoginViewController *)self.window.rootViewController;
rootViewController.managedObjectContext = self.managedObjectContext;

最佳答案

我不完全了解如何将MOC从VC传递到TBVC。通常,RootViewController是TBVC。如果您也是这种情况,则可以通过MOC,如下所示:

#import "AppDelegate.h"
#import "MasterViewController.h"

@implementation AppDelegate

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    UITabBarController *tabController = (UITabBarController *)self.window.rootViewController;

    UINavigationController *navigationController = (UINavigationController *)[[tabController viewControllers] objectAtIndex:0];
    MasterViewController *controller = (MasterViewController *)[[navigationController viewControllers] objectAtIndex:0];
    controller.managedObjectContext = self.managedObjectContext;

    navigationController = (UINavigationController *)[[tabController viewControllers] objectAtIndex:1];
    controller = (MasterViewController *)[[navigationController viewControllers] objectAtIndex:0];
    controller.managedObjectContext = self.managedObjectContext;

    navigationController = (UINavigationController *)[[tabController viewControllers] objectAtIndex:2];
    controller = (MasterViewController *)[[navigationController viewControllers] objectAtIndex:0];
    controller.managedObjectContext = self.managedObjectContext;

    return YES;
}


顺便说一句:此示例基于Xcode中的主从应用程序模板。默认情况下,它没有TBVC,但是如果您添加TBVC(如屏幕截图所示),则上面的代码将起作用。

07-27 16:46