Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get NSManagedObjectContext when using Storyboard

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.

like image 393
mmvie Avatar asked Oct 17 '11 21:10

mmvie


2 Answers

@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;
}
like image 134
badeleux Avatar answered Sep 21 '22 00:09

badeleux


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

like image 44
Roselle Tanner Avatar answered Sep 21 '22 00:09

Roselle Tanner