Thoughts, stories and ideas.

Setting up Core Data

category: programming tags: iOS

Am just beginning to learn Core Data on iOS. Trying to refer to the default template provided by XCode when creating new project, was not of any help in making me understand it better. After reading few tutorials and some coding, here is what I understood:


There are a lot of classes required for setting up and using core data. Here are the common ones and their definitions

  • NSManagedObject - The actual Entity object (managed by core-data and hence a ManagedObject). Eg: "Task", "TaskList", "User"
  • NSManagedObjectContext - Context is where all objects are first either created in memory or fetched to memory as instances of NSManagedObject.
  • NSPersistentStoreCoordinator - The coordinator juggles the persistance of instance of NSManagedObject between disk (NSPersistentStore) and NSManagedContext
  • NSManagedObjectModel - refers to model definition. If your model file is DataModel.xcdatamodeld then managedObjectModel file will be DataModel.momd. the extension momd is important.


   (NSManagedObject *) instance
              |     <- Instance comes from context
              |     <- Context is backed by Coordinator
              |     <- Coordinator writes to store using Model
              |     <- Store writes to file


Main initialization of the context should go into the ApplicationDelegate class.


- (NSManagedObjectContext *)managedObjectContext
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    // First load the Data Model
    // `momd` is important
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"DataModel"
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    NSAssert(_managedObjectModel != nil, @"Managed object model could not be loaded. No pointing in loading the app");

    // Create a coordinator (helper) for objectModel
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:_managedObjectModel];

    // Figure out where to physically store the data
    NSArray *urls = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory
    NSURL *storeURL = [[urls lastObject] URLByAppendingPathComponent:@"store.sqlite"];

    // Ask the coordinator to handle the "NSSqliteStoreType" type of storage
    // At the URL "storeURL"
    NSError *error;
    NSPersistentStore *theStore = [_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
    NSAssert(theStore != nil, @"Attempting to create store which does not exist");

    // Create a actual scratch pad backed by persistent store coordinator
    // which is inturn backed by the an instance of persistent store that is again written to a physical file
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    _managedObjectContext.persistentStoreCoordinator = _persistentStoreCoordinator;

    return _managedObjectContext;