Shared/Persistence/PersistenceController.swift (3716B)
1import CoreData
2import Foundation
3
4
5
6
7
8
9
10
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
22
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
33
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
50
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
67
68
69
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}