Get NSManagedObjectContext when using Storyboard

2020-06-03 06:07发布

问题:

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