将managedObjectContext(核心数据)传递给其他类,正确完成了吗?

all*_*ire 4 iphone core-data objective-c ios

我使用Apple提供的Core Data的默认模板(managedObjectContext在AppDelegate中).起初我在每个需要使用managedObjectContext的类中都包含了appdelegate.h,但是我发现这不是正确的方法.Apple说最好只将上下文传递给需要它的其他类等等,所以我最终这样做了.事情是,它看起来有点"黑客"我做的方式,我想知道是否有更好的选择或我的解决方案是正确的.

我的应用程序目前设置如此(这是我的故事板的SS): 在此输入图像描述

所以我的根窗口是一个UITabBarController,每个选项卡都是一个指向多个UITableViewController/UIViewController的UINavigationController.

以下是我在Appdelegate中将managedObjectContext实例传递给2个选项卡的内容:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    UITabBarController *rootViewController;
    UINavigationController *navigationController;
    ItemsTableViewController *itemsTableViewController;

    // Get the root window (UITabBarController)
    rootViewController = (UITabBarController *)self.window.rootViewController;


    // Get the second item of the UITabBarController
    navigationController = [[rootViewController viewControllers] objectAtIndex:1];

    // Get the first item of the UINavigationController (ItemsTableViewController)
    itemsTableViewController = [[navigationController viewControllers] objectAtIndex:0];
    itemsTableViewController.managedObjectContext = self.managedObjectContext;


    // Get the third item of the UITabBarController (again ItemsTableViewController)
    navigationController = [[rootViewController viewControllers] objectAtIndex:2];

    // Get the first item of the UINavigationController (ItemsTableViewController)
    itemsTableViewController = [[navigationController viewControllers] objectAtIndex:0];    
    itemsTableViewController.managedObjectContext = self.managedObjectContext;

    return YES;
}
Run Code Online (Sandbox Code Playgroud)

一切都运行良好,但不得不多次调用objectAtIndex来到正确的ViewController看起来...

有人作为更好的解决方案?

谢谢!

Rog*_*Rog 10

您应该查看使用该prepareForSegue:方法将managedObjectContext传递给其他控制器.

或者,您可以对选项卡栏控制器进行子类化,并将托管对象上下文添加为属性,然后您可以从应用程序中的任何位置访问该属性,前提是标签栏控制器也在那里.

最后,如果您只打算使用一个上下文(即没有多线程),您总是可以CoreDataHelper使用类方法设置一个类,该方法在您请求时返回默认上下文.为了避免在每个类中导入帮助器,只需将助手添加到预编译的头文件(.pch)中,然后让它也导入<CoreData/CoreData.h>框架.

如果你想看一个如何完成这个的例子,请在github上查看MagicalRecord https://github.com/magicalpanda/MagicalRecord

[编辑]以下是如何使用该prepareForSegue方法传递上下文的示例.请记住,当segue即将启动时调用此方法,它使您有机会设置即将推送的视图控制器.您可以在此处传递委托引用并将值分配给目标视图控制器中的其他变量:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    NSString *segueIdentifier = [segue identifier];
    if ([segueIdentifier isEqualToString:@"YourSegueIdentifier"]) // This can be defined via Interface Builder
    {
        MyCustomViewController *vc = [segue destinationViewController];
        vc.managedObjectContext = self.managedObjectContext;
    }
}
Run Code Online (Sandbox Code Playgroud)