This chapter shows you how to create and configure the Core Data stack, from the managed object context to the underlying persistent store. Creating the context is easy—you simply have to allocate and initialize an instance of NSManagedObjectContext. The more complex part is the remainder of the configuration. You must create and configure a persistent store coordinator, and then set up the persistent stores.
The managed object context is responsible for managing the object graph. The task of managing the persistent stores falls to the persistent store coordinator. Its job is to mediate between the managed object context or contexts and the persistent store or stores. It presents a façade to the contexts, representing a collection of stores as a single virtual store. In this example, the coordinator manages just a single store.
To add a store, you use the NSPersistentStoreCoordinator method addPersistentStoreWithType:configuration:URL:options:error:. This returns an object representing the new store, or nil if it cannot be created. (There is currently no public API to manipulate store instances; they may be used, however, as arguments to other methods of NSPersistentStoreCoordinator.) You must specify both the store’s location in the file system and its type (this example does not make use of model configurations). In this example it is an XML store—because its reasonably human-readable form facilitates testing. Note that the file name extension is not .xml. You should avoid using generic file extensions—consider what would happen if all applications used the same extension. . .
The managedObjectContext Function
Build and Test
Complete Listing
Last updated: 2008-02-08