NSPersistentContainer

Core Data is represented by a collection of classes often referred to as the Core Data stack. This collection of classes is abstracted away from you via the NSPersistentContainer class. You will learn more about the Core Data stack classes in the For the More Curious section at the end of this chapter.

To use Core Data, you will need to import the Core Data framework in the files that need it.

Open PhotoStore.swift and import Core Data at the top of the file.

Listing 22.2  Importing Core Data (PhotoStore.swift)

import UIKit
import CoreData

Also in PhotoStore.swift, add a property to hold on to an instance of NSPersistentContainer.

Listing 22.3  Adding an NSPersistentContainer property (PhotoStore.swift)

class PhotoStore {

    let imageStore = ImageStore()

    let persistentContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "Photorama")
        container.loadPersistentStores { (description, error) in
            if let error = error {
                print("Error setting up Core Data ((error)).")
            }
        }
        return container
    }()

You instantiate an NSPersistentContainer with a name. This name must match the name of the data model file that describes your entities. After creating the container, it needs to load its persistent stores. The store is where the data is actually stored on disk. By default, this is going to be a SQLite database. Due to the possibility of this operation taking some time, loading the persistent stores is an asynchronous operation that calls a completion handler when complete.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset