← All repositories

reportage

A life-logging app for iPhone

git clone https://code.inqk.net/reportage.git


Shared/Persistence/PersistenceController.swift (3716B)

1import CoreData
2import Foundation
3
4/// Wraps the app's `NSPersistentContainer`. Plain Core Data with no CloudKit
5/// mirroring: sync is the job of a separate `CKSyncEngine` layer that drives
6/// CloudKit directly on top of this store.
7///
8/// `@unchecked Sendable` because the only stored property is the container,
9/// whose `viewContext` is main-queue confined and whose
10/// `newBackgroundContext()` is safe to call from any thread.
11final class PersistenceController: @unchecked Sendable {
12    let container: NSPersistentContainer
13
14    var viewContext: NSManagedObjectContext { container.viewContext }
15
16    init(inMemory: Bool = false, storeURL: URL? = nil) {
17        container = NSPersistentContainer(
18            name: "ReportageModel", managedObjectModel: Self.sharedModel)
19
20        if inMemory {
21            // NSInMemoryStoreType keeps each store isolated in process memory,
22            // so tests can't collide through shared SQLite files.
23            let description = NSPersistentStoreDescription()
24            description.type = NSInMemoryStoreType
25            container.persistentStoreDescriptions = [description]
26        } else if let storeURL {
27            container.persistentStoreDescriptions = [NSPersistentStoreDescription(url: storeURL)]
28        }
29        for description in container.persistentStoreDescriptions {
30            description.shouldMigrateStoreAutomatically = true
31            description.shouldInferMappingModelAutomatically = true
32            // A migration that drops data frees space SQLite keeps for reuse
33            // rather than returning, so the file is rebuilt after one.
34            if Self.needsMigration(description) {
35                description.setOption(true as NSNumber, forKey: NSSQLiteManualVacuumOption)
36            }
37        }
38
39        container.loadPersistentStores { _, error in
40            if let error {
41                fatalError("Failed to load Core Data store: \(error)")
42            }
43        }
44
45        container.viewContext.automaticallyMergesChangesFromParent = true
46        container.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
47    }
48
49    /// Whether the SQLite store at `description` exists and was made with an
50    /// earlier model.
51    private static func needsMigration(_ description: NSPersistentStoreDescription) -> Bool {
52        guard description.type == NSSQLiteStoreType, let url = description.url,
53            FileManager.default.fileExists(atPath: url.path),
54            let metadata = try? NSPersistentStoreCoordinator.metadataForPersistentStore(
55                type: .sqlite, at: url)
56        else { return false }
57        return !sharedModel.isConfiguration(withName: description.configuration, compatibleWithStoreMetadata: metadata)
58    }
59
60    func newBackgroundContext() -> NSManagedObjectContext {
61        let context = container.newBackgroundContext()
62        context.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
63        return context
64    }
65
66    /// Loaded once per process. Each `NSManagedObjectModel` instance registers
67    /// its entity classes, so loading the model per container (as tests do)
68    /// would make several descriptions claim the same class. A model is
69    /// immutable once a coordinator uses it, so sharing it is safe.
70    nonisolated(unsafe) private static let sharedModel: NSManagedObjectModel = {
71        for bundle in Bundle.allBundles + Bundle.allFrameworks {
72            if let url = bundle.url(forResource: "ReportageModel", withExtension: "momd"),
73                let model = NSManagedObjectModel(contentsOf: url)
74            {
75                return model
76            }
77        }
78        fatalError("ReportageModel.momd not found in any loaded bundle")
79    }()
80}