Get NSManagedObjectContext when using Storyboard

六月ゝ 毕业季﹏ 提交于 2019-12-03 17:24:53

问题


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)];

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.


回答1:


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

From 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;
}



回答2:


I don't know if this is what you need, but it may help:
id appDelegate = (id)[[UIApplication sharedApplication] delegate]; self.managedObjectContext = [appDelegate managedObjectContext];



来源:https://stackoverflow.com/questions/7799625/get-nsmanagedobjectcontext-when-using-storyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!