4

Well I was reading the Core Data tutorial for iOS on Apple's website and I don't quite get it.

How do I actually obtain the NSManagedObjectContext so I can use it to access to my database?

Abizern
  • 146,289
  • 39
  • 203
  • 257
Samuli Lehtonen
  • 3,840
  • 5
  • 39
  • 49

1 Answers1

5

If you need to create a new context, just use alloc/init and then add a persistent store coordinator. This is described in Creating a New Managed Object Context. If you've already created a context in, say, your app delegate or root view controller, then you just need to pass it into your view controller when the controller is created. For example, the app delegate typically creates the root view controller. The app delegate can create the managed object context and then set the context in the controller.

Caleb
  • 124,013
  • 19
  • 183
  • 272
  • Ok I'll try to make it in app delegate and create a method which returns it. – Samuli Lehtonen Jul 05 '11 at 14:58
  • Can't seem to figure how I get the store coordinator first. – Samuli Lehtonen Jul 05 '11 at 15:08
  • 1
    Sorry -- link was slighly off. Fixed now. To create the persistent store coordinator, again, use `+alloc`, and then call `-initWithManagedObjectModel:`. How do you get a model? There are a few methods, but `+mergedModelFromBundles:` is a good choice to get you started. Hint: if you create a new project and check the 'use Core Data' box in Xcode, you'll find some good starter code that sets all this stuff up in the app delegate. – Caleb Jul 05 '11 at 15:19
  • Is this correct? `managedObjectModel_ = [NSManagedObjectModel mergedModelFromBundles:[NSArray arrayWithObject:[NSBundle mainBundle]]]; persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel_]; managedObjectContext_ = [[NSManagedObjectContext alloc] init]; [managedObjectContext_ setPersistentStoreCoordinator:persistentStoreCoordinator_];` – Samuli Lehtonen Jul 05 '11 at 15:29
  • Look at the app delegate in a template project in Xcode that uses Core Data. That will provide all the boilerplate you need for a simple Core Data based app. – TechZen Jul 05 '11 at 17:11