Setting Up a Core Data Stack Manually


NSPersistentContainer is supported in iOS 10.0+ and macOS 10.12+. If you’re deploying to an earlier target, you need to manually instantiate an NSManagedObjectModel, an NSPersistentStoreCoordinator, and at least one NSManagedObjectContext.

Create a Managed Object Model

To instantiate an NSManagedObjectModel, you pass in a URL that points to the compiled version of the .xcdatamodeld file. This .momd file is typically part of your app bundle.

guard let modelURL = Bundle.main.url(forResource: "DataModel",
                                     withExtension: "momd") else {
    fatalError("Failed to find data model")
guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
    fatalError("Failed to create model from file: \(modelURL)")

Create a Persistent Store Coordinator

Next, you pass the loaded model into the NSPersistentStoreCoordinator initializer, to create a store coordinator associated with the model.

let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)

Add a Persistent Store

If you want Core Data to persist your data model to disk, tell the store coordinator where the file will reside and what format to use.

let dirURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last
let fileURL = URL(string: "DataModel.sql", relativeTo: dirURL)
do {
    try psc.addPersistentStore(ofType: NSSQLiteStoreType,
                               configurationName: nil,
                               at: fileURL, options: nil)
} catch {
    fatalError("Error configuring persistent store: \(error)")

There are advantages and disadvantages to each of the available store types. Refer to the NSPersistentStoreCoordinator documentation for details on each store type.

Create a Managed Object Context

Create an NSManagedObjectContext, and set its store coordinator property.

let moc = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
moc.persistentStoreCoordinator = psc

The bulk of your app’s interaction with Core Data will be with this context. Pass this context by reference to your user interface. See Pass a Persistent Container Reference to a View Controller.