فهرست منبع

Remove lazy init for persistent container; adjust accordingly; add back 1 debug print

Deniz Cengiz 1 سال پیش
والد
کامیت
38b0ae5da1
1فایلهای تغییر یافته به همراه46 افزوده شده و 58 حذف شده
  1. 46 58
      Model/CoreDataStack.swift

+ 46 - 58
Model/CoreDataStack.swift

@@ -9,20 +9,52 @@ class CoreDataStack: ObservableObject {
     private var notificationToken: NSObjectProtocol?
     private var notificationToken: NSObjectProtocol?
     private let inMemory: Bool
     private let inMemory: Bool
 
 
+    let persistentContainer: NSPersistentContainer
+    
     private init(inMemory: Bool = false) {
     private init(inMemory: Bool = false) {
-        self.inMemory = inMemory
-
-        // Observe Core Data remote change notifications on the queue where the changes were made
-        notificationToken = Foundation.NotificationCenter.default.addObserver(
-            forName: .NSPersistentStoreRemoteChange,
-            object: nil,
-            queue: nil
-        ) { _ in
-            Task {
-                await self.fetchPersistentHistory()
+            self.inMemory = inMemory
+
+            // Initialize persistent container immediately
+            persistentContainer = NSPersistentContainer(
+                name: "TrioCoreDataPersistentContainer",
+                managedObjectModel: Self.managedObjectModel
+            )
+
+            guard let description = persistentContainer.persistentStoreDescriptions.first else {
+                fatalError("Failed \(DebuggingIdentifiers.failed) to retrieve a persistent store description")
+            }
+
+            if inMemory {
+                description.url = URL(fileURLWithPath: "/dev/null")
+            }
+
+            description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
+            description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
+            description.shouldMigrateStoreAutomatically = true
+            description.shouldInferMappingModelAutomatically = true
+
+            persistentContainer.loadPersistentStores { _, error in
+                if let error = error as NSError? {
+                    fatalError("Unresolved Error \(DebuggingIdentifiers.failed) \(error), \(error.userInfo)")
+                }
+            }
+
+            persistentContainer.viewContext.automaticallyMergesChangesFromParent = false
+            persistentContainer.viewContext.name = "viewContext"
+            persistentContainer.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
+            persistentContainer.viewContext.undoManager = nil
+            persistentContainer.viewContext.shouldDeleteInaccessibleFaults = true
+
+            notificationToken = Foundation.NotificationCenter.default.addObserver(
+                forName: .NSPersistentStoreRemoteChange,
+                object: nil,
+                queue: nil
+            ) { _ in
+                Task {
+                    await self.fetchPersistentHistory()
+                }
             }
             }
         }
         }
-    }
 
 
     deinit {
     deinit {
         if let observer = notificationToken {
         if let observer = notificationToken {
@@ -70,50 +102,6 @@ class CoreDataStack: ObservableObject {
         return model
         return model
     }()
     }()
 
 
-    /// A persistent container to set up the Core Data Stack
-    lazy var persistentContainer: NSPersistentContainer = {
-        // Use shared model instead of loading a new one
-        let container = NSPersistentContainer(
-            name: "TrioCoreDataPersistentContainer",
-            managedObjectModel: Self.managedObjectModel
-        )
-
-        guard let description = container.persistentStoreDescriptions.first else {
-            fatalError("Failed \(DebuggingIdentifiers.failed) to retrieve a persistent store description")
-        }
-
-        if inMemory {
-            description.url = URL(fileURLWithPath: "/dev/null")
-        }
-
-        // Enable persistent store remote change notifications
-        /// - Tag: persistentStoreRemoteChange
-        description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
-
-        // Enable persistent history tracking
-        /// - Tag: persistentHistoryTracking
-        description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
-
-        // Enable lightweight migration
-        /// - Tag: lightweightMigration
-        description.shouldMigrateStoreAutomatically = true
-        description.shouldInferMappingModelAutomatically = true
-
-        container.loadPersistentStores { _, error in
-            if let error = error as NSError? {
-                fatalError("Unresolved Error \(DebuggingIdentifiers.failed) \(error), \(error.userInfo)")
-            }
-        }
-
-        container.viewContext.automaticallyMergesChangesFromParent = false
-        container.viewContext.name = "viewContext"
-        /// - Tag: viewContextmergePolicy
-        container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
-        container.viewContext.undoManager = nil
-        container.viewContext.shouldDeleteInaccessibleFaults = true
-        return container
-    }()
-
     /// Creates and configures a private queue context
     /// Creates and configures a private queue context
     func newTaskContext() -> NSManagedObjectContext {
     func newTaskContext() -> NSManagedObjectContext {
         // Create a private queue context
         // Create a private queue context
@@ -507,9 +495,9 @@ extension NSManagedObjectContext {
         do {
         do {
             guard onContext.hasChanges else { return }
             guard onContext.hasChanges else { return }
             try onContext.save()
             try onContext.save()
-//            debug(.coreData,
-//                "Saving to Core Data successful in \(callingFunction) in \(callingClass): \(DebuggingIdentifiers.succeeded)"
-//            )
+            debug(.coreData,
+                "Saving to Core Data successful in \(callingFunction) in \(callingClass): \(DebuggingIdentifiers.succeeded)"
+            )
         } catch let error as NSError {
         } catch let error as NSError {
             debug(
             debug(
                 .coreData,
                 .coreData,