Singleton managedObjectContext

3.3k views Asked by At

I want to use the singleton UIApplication to access the managedObjectContext of the AppDelegate. But when I write

[[[UIApplication sharedApplication] delegate] managedObjectContext]

or

[[[UIApplication sharedApplication] delegate] __managedObjectContext]

it doesn't work.

But this line works fine :

NSLog(@"Seeking for the AppDelegate : %@", [[[UIApplication sharedApplication] delegate] class]);

Do you have a solution ? Niels

2

There are 2 answers

3
uvesten On BEST ANSWER

Try casting it to your actual app delegate implementation, like

 [(MyAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];

And to add

#import "MyAppDelegate.h"

at the top of the file.

2
Mike Weller On

Using a singleton like this is bad practice, and even explicitly discouraged in the Core Data documentation:

http://developer.apple.com/library/ios/#documentation/DataManagement/Conceptual/CoreDataSnippets/Articles/stack.html

A view controller typically shouldn’t retrieve the context from a global object such as the application delegate. This tends to make the application architecture rigid. Neither should a view controller typically create a context for its own use. 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.

When you create a view controller, you pass it a context. You pass an existing context, or (in a situation where you want the new controller to manage a discrete set of edits) a new context that you create for it. It’s typically the responsibility of the application delegate to create a context to pass to the first view controller that’s displayed.

Dependency injection (i.e. giving the view controller what it needs) is better in almost all situations. It really isn't good to see [[UIApplication sharedApplication] delegate] all over an application's code because it makes the code hard to reuse, hard to write tests for, etc.