Get NSManagedObjectContext when using Storyboard
Asked Answered
M

2

10

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.

Margerymarget answered 17/10, 2011 at 21:12 Comment(0)
A
12

@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;
}
Aberrant answered 6/12, 2012 at 9:39 Comment(3)
Though this topic is old, you're correct and hence I've marked it as the correct answer.Margerymarget
what if you want to pass a view controller the managed object context and it's nowhere near applicationDidFinishLaunching? It is only created 5 levels deep somewhere else in my app.Cutcherry
@Cutcherry It's not bad practice to inject it. Please have a look at DependencyInjection frameworks available in iOS platformAberrant
C
11

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

Charmian answered 18/10, 2011 at 19:35 Comment(1)
I guess I spent way too much time trying to figure out how to pass the [managedObjectContext] from the app delegate to the view, of course a better solution is just to get the moc from the appdelegate. Awesome!Implosive

© 2022 - 2024 — McMap. All rights reserved.