Mac OS X Reference Library Apple Developer Connection spyglass button

Creating the Core Data Stack

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

The main purpose of the managedObjectContext function is to return a properly configured managed object context. In this example, in order to do so you must also configure the remainder of the Core Data stack.

Create the Context Instance

The first step is to create the managed object context instance itself, if necessary.

  1. At the top of the main source file, before main add a declaration for the function NSManagedObjectContext *managedObjectContext().

  2. In the main source file, implement the managedObjectContext function. Declare a static variable for the context. If the variable is not nil return it immediately. If it is nil, create a new context, then return it as the function result.

    NSManagedObjectContext *managedObjectContext()
    {
        static NSManagedObjectContext *moc = nil;
        if (moc != nil) {
            return moc;
        }
     
        moc = [[NSManagedObjectContext alloc] init];
     
        // implementation continues...
     
        return moc;
    }

Set up the Persistent Store Coordinator and Store

The second step is to create the persistent store coordinator and configure the persistent store.

  1. Create a persistent store coordinator, then set the coordinator for the context.

    NSPersistentStoreCoordinator *coordinator =
            [[NSPersistentStoreCoordinator alloc]
                    initWithManagedObjectModel: managedObjectModel()];
    [moc setPersistentStoreCoordinator: coordinator];
  2. Create a new persistent store of the appropriate type. If for some reason the store cannot be created, log an appropriate warning.

    NSString *STORE_TYPE = NSXMLStoreType;
    NSString *STORE_FILENAME = @"CDCLI.cdcli";
     
    NSError *error;
    NSURL *url = [NSURL fileURLWithPath:
            [applicationLogDirectory() stringByAppendingPathComponent:STORE_FILENAME]];
     
    NSPersistentStore *newStore = [coordinator addPersistentStoreWithType:STORE_TYPE
                                            configuration:nil
                                                      URL:url
                                                  options:nil
                                                    error:&error];
     
    if (newStore == nil) {
        NSLog(@"Store Configuration Failure\n%@",
                ([error localizedDescription] != nil) ?
                [error localizedDescription] : @"Unknown Error");
    }

Instantiate a Managed Object Context

So that you can test the implementation thus far, instantiate the managed object context.

  1. In the main function, after the line in which the description of the managed object model is logged, declare a variable of type NSManagedObjectContext and assign its value to the result of invoking the managedObjectContext function.

    NSManagedObjectContext *moc = managedObjectContext();

Build and Test

Build and run the utility. It should compile without errors, although you should get a warning that the variable moc is unused in the main function. When you run the utility, the managedObjectContext function should not log any errors.

Complete Listing

The complete listing of the managedObjectContext function is shown in Listing 5-1.

Listing 5-1  Complete listing of the managedObjectContext function

NSManagedObjectContext *managedObjectContext()
{
    static NSManagedObjectContext *moc = nil;
 
    if (moc != nil) {
        return moc;
    }
 
    moc = [[NSManagedObjectContext alloc] init];
 
    NSPersistentStoreCoordinator *coordinator =
        [[NSPersistentStoreCoordinator alloc]
                initWithManagedObjectModel: managedObjectModel()];
    [moc setPersistentStoreCoordinator: coordinator];
 
    NSString *STORE_TYPE = NSXMLStoreType;
    NSString *STORE_FILENAME = @"CDCLI.cdcli";
 
    NSError *error;
    NSURL *url = [NSURL fileURLWithPath:
        [applicationLogDirectory() stringByAppendingPathComponent:STORE_FILENAME]];
 
    NSPersistentStore *newStore = [coordinator addPersistentStoreWithType:STORE_TYPE
                                            configuration:nil
                                                      URL:url
                                                  options:nil
                                                    error:&error];
 
    if (newStore == nil) {
        NSLog(@"Store Configuration Failure\n%@",
                ([error localizedDescription] != nil) ?
                [error localizedDescription] : @"Unknown Error");
    }
    return moc;
}


Last updated: 2009-03-04

Did this document help you? Yes It's good, but... Not helpful...