使用故事板时获取NSManagedObjectContext [英] Get NSManagedObjectContext when using Storyboard

查看:154
本文介绍了使用故事板时获取NSManagedObjectContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标是获取当前的NSManagedObjectContext以便使用Core Data。在iOS 4.3中,我将UINavigationController的代理设置为AppDelegate(在AppDelegate.m中):

The objective is to get the current NSManagedObjectContext in order to work with Core Data. In iOS 4.3 I set the UINavigationController's delegate to be the AppDelegate like so (in AppDelegate.m):

self.navigationController.delegate = self;

我可以做这样的事情(无论我需要上下文):

and I could do something like this (wherever I needed the context):

NSManagedObjectContext *context = [self.navigationController.delegate performSelector:@selector(managedObjectContext)];

现在,在iOS 5中,我正在使用一个故事板,我很难想出怎么实现呢我使用了一个代表,因为我不认为你想让你的AppDelegate.h在所有的时间。

Now, in iOS 5, I am using a Storyboard and I'm having a difficult time figuring out how to achieve this. I used a delegate in the first place because I don't think you want to be passing your AppDelegate.h around all the time.

推荐答案

@Rose - 再次?即使是苹果也非常不鼓励:

@Rose - Again? It is highly discouraged even by Apple:

从Apple Doc


视图控制器通常不应从全局对象,如应用程序委托 - 这使应用程序架构变得僵硬。视图控制器也不应该为自己的使用创建上下文(除非是嵌套的上下文)。这可能意味着使用控制器的上下文执行的操作没有注册到其他上下文,因此不同的视图控制器将对数据有不同的观点。

A view controller typically shouldn’t retrieve the context from a global object such as the application delegate—this makes the application architecture rigid. Neither should a view controller create a context for its own use (unless it’s a nested context). This may mean that operations performed using the controller’s context aren’t registered with other contexts, so different view controllers will have different perspectives on the data.

推荐方法:

Recommended way:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:    (NSDictionary *)launchOptions
{
// Override point for customization after application launch.
UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;
MasterViewController *controller = (MasterViewController *)navigationController.topViewController;
controller.managedObjectContext = self.managedObjectContext;
return YES;
}

这篇关于使用故事板时获取NSManagedObjectContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆