Swift Core Data: ManagedObjectModel, PersistentStoreCoordinator and MainObjectContext

So I’m starting to dive into Core Data at work.  Core Data is more than just a database.  Among other things, it manages the database for you which is very handy, especially when a database update is needed.

Today, we made a Core Data manager that initializes Core Data for use in my app.  It initializes the Managed Object Model, the Persistent Store Coordinator and the Main Object Context.

-Managed Object Model

This is the structure of the database.  Generally, you’ll create this in your .xcdatamodel file.  It’s initialized by referring to that file:

        self.managedObjectModel =  NSManagedObjectModel(contentsOfURL: modelUrl)!

-Persistent Store Coordinator

This object coordinates the data with the managed object model to create the database:

       self.persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)

-Main Object Context

This object is the way the app communicates with the database.  So a swift way of creating the data manager class might look like this (including a save function- pretty important for a database):

 

import Foundation

import CoreData

final class CoreDataManager {

    

    private let managedObjectModel: NSManagedObjectModel

    private let persistentStoreCoordinator: NSPersistentStoreCoordinator

    let mainObjectContext: NSManagedObjectContext

    

    init() {

        //    //Get the Object Model

        let modelUrl: NSURL = NSBundle.mainBundle().URLForResource("YourXCDatamodelFileName", withExtension: "momd")!

        

        self.managedObjectModel =  NSManagedObjectModel(contentsOfURL: modelUrl)!

        let paths = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)

        let storeURL: NSURL = paths[0].URLByAppendingPathComponent("NotificationModel.sqlite")

        

        let options = [NSMigratePersistentStoresAutomaticallyOption: true,

                        NSInferMappingModelAutomaticallyOption: true]

        

        self.persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)

        do {

            try self.persistentStoreCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: options)

        } catch {

            fatalError("Error migrating store: \(error)")

        }

        

        self.mainObjectContext =  NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)

        mainObjectContext.persistentStoreCoordinator = persistentStoreCoordinator

    }

    

    func save() {

        do {

            try mainObjectContext.save()

        } catch {

            fatalError("Error while saving: \(error)")

        }

    }

}

ps. I take no credit for this code – it’s mostly pilfered and/or translated from Objective C

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>