iOS Roadmap

Module 1 of 11 0%

#Core Data Storage

5. Initializing the Core Data storage

Our next step is creating a persistence service which will allow us to access and interact with our Core Data logic. Let’s start by creating our class:

// 1.
import CoreData

// 2.
final class PersistenceService {}
  1. We import CoreData to be able to gain access to all Core Data functionalities;
  2. We create a PersistenceService class, which we will use to interact with Core Data logic;

Let’s continue by setting up Core Data. Create a reference to NSPersistentContainer and initialize it with our CoreDataModel that we created.

import CoreData

final class PersistenceService {

    // MARK: - Properties

    private let persistentContainer: NSPersistentContainer

    // MARK: - Initialziers

    init() {
        persistentContainer = NSPersistentContainer(name: "CoreDataModel")
        persistentContainer.loadPersistentStores { _, error in
            if let error {
                preconditionFailure()
            }
        }
    }
}

First, we initialize our NSPersistentContainer. This persistent container is responsible for setting up everything - from connecting our Core Data model to setting up our underlying persistent solution, whether it’s SQLite, XML (OSX only), Binary Data or In-Memory.

In the initializer, we’re basically specifying that the persistent container should reference the Core Data model that we created previously. Finally, we call loadPersistentStores to initialize the underlying persistent storage - which by default is SQLite. If something fails during this step, we simply call a preconditionFailure(), since this is a fatal error in our application and the user shouldn’t be able to continue.

With this, we’re ready to start persisting our entities.