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?
First you need to create a property in your
AppDelegate.hlike the following:Using
readonlyprevent you to modify the context externally.In
AppDelegate.msynthesize it like:Always within the
AppDelegate.moverride the getter method likeOnce done you have a
managedObjectContextproperty which can be accessed anywhere withA more cool approach could be to create a class method in your
AppDelegate.hlike the following:Then in
AppDelegate.mdo like the following:Now, anywhere, before having imported your
AppDelegateheader (#import "AppDelegate.h"), you can do: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.