ilight
ilight

Reputation: 1622

Setting ViewController's managedObjectContext

I am using CoreData and I set the NSManagedObjectContext in AppDelegate file.

I need to get that managedObjectContext in a ViewController which is many levels deep in the naviagation tree. Obviously, I do not want to pass it along all the init methods.

I have tried [[[UIApplication sharedApplication] delegate] managedObjectContext]; but I get this error "No known instance method for selector 'managedObjectContext'"

Can someone guide me on how to get the managedObjectContext from AppDelegate to this ViewContoller?

Upvotes: 3

Views: 6365

Answers (2)

Lorenzo B
Lorenzo B

Reputation: 33428

First you need to create a property in your AppDelegate.h like the following:

@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext; // or strong if you ARC instead of retain

Using readonly prevent you to modify the context externally.

In AppDelegate.m synthesize it like:

@synthesize managedObjectContext;

Always within the AppDelegate.m override the getter method like

- (NSManagedObjectContext *)managedObjectContext
{    
    if (managedObjectContext != nil) return managedObjectContext;

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {

        managedObjectContext = [[NSManagedObjectContext alloc] init];
        [managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return managedObjectContext;
}

Once done you have a managedObjectContext property which can be accessed anywhere with

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext* context = appDelegate.managedObjectContext;

A more cool approach could be to create a class method in your AppDelegate.h like the following:

+ (AppDelegate *)sharedAppDelegate;

Then in AppDelegate.m do like the following:

+ (AppDelegate *)sharedAppDelegate
{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

Now, anywhere, before having imported your AppDelegate header (#import "AppDelegate.h"), you can do:

AppDelegate* appDelegate = [AppDelegate sharedAppDelegate];
NSManagedObjectContext* context = appDelegate.managedObjectContext;

Note

Using such an approach causes your application to become rigid. To overcome this problem I suggest you to read about passing-around-a-nsmanagedobjectcontext-on-the-iphone by Marcus Zarra.

Hope it helps.

Upvotes: 14

melsam
melsam

Reputation: 4977

You need to cast the global sharedApplication variable into your own app's AppDelegate class. Here's an example:

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];            
// Now you can access appDelegate.managedObjectContext;

Note: you'll need to #import "AppDelegate.h" in the .m file where you use this code.

Upvotes: 2

Related Questions