我使用了 Apple 提供的带有 Core Data 的默认模板(managedObjectContext 在 AppDelegate 中)。起初,我在每个需要使用 managedObjectContext 的类中都包含了 appdelegate.h,但我发现这不是正确的方法。 Apple 说最好只将上下文传递给其他需要它的类等等,所以我最终就是这样做的。问题是,我这样做的方式看起来有点“骇人听闻”,我想知道是否有更好的选择或者我的解决方案是否正确。
我的应用目前是这样设置的(这是我的 Storyboard的 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;
}
一切正常,但必须多次调用 objectAtIndex 才能到达正确的 ViewController 看起来很糟糕......
谁有更好的解决方案?
谢谢!
最佳答案
你应该看看使用 prepareForSegue:
方法将您的 managedObjectContext 传递给其他 Controller 。
或者,您可以子类化标签栏 Controller 并将托管对象上下文添加为一个属性,然后您可以从您的应用程序中的任何地方访问它,前提是标签栏 Controller 也在那里。
最后,如果你只打算使用一个上下文(即没有多线程),你总是可以设置一个 CoreDataHelper
使用类方法进行类处理,该类方法会在您需要时返回您的默认上下文。为避免在每个类中导入助手,只需将助手添加到预编译头文件 (.pch) 并让它也导入 <CoreData/CoreData.h>
框架。
如果您想查看如何完成此操作的示例,请查看 github 上的 MagicalRecord https://github.com/magicalpanda/MagicalRecord
[编辑]
这是一个如何使用 prepareForSegue
传递上下文的示例方法。请记住,当 segue 即将启动时会调用此方法,它使您有机会设置即将被推送的 View Controller 。这是您可以传递委托(delegate)引用并为目标 View Controller 中的其他变量赋值的地方:
- (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;
}
}
关于iphone - 将 managedObjectContext(核心数据)传递给其他类,正确完成了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8888595/