views:

421

answers:

2

I've recently created a project using Core Data. I checked where xcode ask you if you want to use Core data or not and I have the core data generated code in my app delegate. I've gotten it to work after many hours of doing research. Here is what I've done to get it to work:

  1. created an instance of the managedObjectContext in the app delegate
  2. pass that instance to an object that would be doing Core data calls for instance
    managedObjectContext = [self managedObjectContext ];
    //the above code initializes all the other generated variables on the MOC

    DBLayer dblayer = [[[DBLayer alloc] init];
    dblayer.moc = managedObjectContext;

You would think that you could copy all the generated code from the app delegate to a new object and it would work fine, but it didn't for me.

So, basically my question is do you have to create the managedObjectContext in the app delegate and pass it around to whomever needs it or is there a simpiler way?

The reason I ask is because there are some objects that need to make database calls and I've having to pass the instance of managedObjectContext to them from the app delegate.

Thanks to all that reply

A: 

In my project, most of my "CoreData Stack" was retyped using the CoreData template as an example. The code in the application delegate essentially instantiates the Core Data stack, gets the stores ready, all that fun stuff.

The main object you're going to be dealing with (most of the time) is a Managed Object Context. It's perfectly fine to pass the same one around (most of the time, there are times however when you'll need another, and have to merge them, but it's rare). What I do is pass the application delegate's MOC down to my root view controller, which then passes it to any other view controllers which need it.

So, create the stack in the App Delegate, then pass that Managed Object Context around to your view controllers as needed (an alternative is to just access it directly, like a singleton, from your App Delegate, when it's needed. This way you don't have to pass it down through your whole navigation stack, it can just be retrieved when it's needed. This is not what I have done, but it is certainly a valid way to access your stack).

jbrennan
A: 

The answer strictly depends on your application needs. For instance, your application may need multiple contexts handled by several different threads, or you may have as in the case you describe, just a single context. In the latter case, the obvious/common way of managing this is exactly to pass around the managed object context to the controller that needs it.

unforgiven