CoreDataStack.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. import CoreData
  2. import Foundation
  3. import OSLog
  4. class CoreDataStack: ObservableObject {
  5. static let shared = CoreDataStack()
  6. static let identifier = "CoreDataStack"
  7. private var notificationToken: NSObjectProtocol?
  8. private let inMemory: Bool
  9. private init(inMemory: Bool = false) {
  10. self.inMemory = inMemory
  11. // Observe Core Data remote change notifications on the queue where the changes were made
  12. notificationToken = Foundation.NotificationCenter.default.addObserver(
  13. forName: .NSPersistentStoreRemoteChange,
  14. object: nil,
  15. queue: nil
  16. ) { _ in
  17. debugPrint("Received a persistent store remote change notification")
  18. Task {
  19. await self.fetchPersistentHistory()
  20. }
  21. }
  22. }
  23. deinit {
  24. if let observer = notificationToken {
  25. Foundation.NotificationCenter.default.removeObserver(observer)
  26. }
  27. }
  28. /// A persistent history token used for fetching transactions from the store
  29. private var lastToken: NSPersistentHistoryToken?
  30. /// A persistent container to set up the Core Data Stack
  31. lazy var persistentContainer: NSPersistentContainer = {
  32. let container = NSPersistentContainer(name: "Core_Data")
  33. guard let description = container.persistentStoreDescriptions.first else {
  34. fatalError("Failed \(DebuggingIdentifiers.failed) to retrieve a persistent store description")
  35. }
  36. if inMemory {
  37. description.url = URL(fileURLWithPath: "/dev/null")
  38. }
  39. // Enable persistent store remote change notifications
  40. /// - Tag: persistentStoreRemoteChange
  41. description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
  42. // Enable persistent history tracking
  43. /// - Tag: persistentHistoryTracking
  44. description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
  45. container.loadPersistentStores { _, error in
  46. if let error = error as NSError? {
  47. fatalError("Unresolved Error \(DebuggingIdentifiers.failed) \(error), \(error.userInfo)")
  48. }
  49. }
  50. container.viewContext.automaticallyMergesChangesFromParent = false
  51. container.viewContext.name = "viewContext"
  52. /// - Tag: viewContextmergePolicy
  53. container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
  54. container.viewContext.undoManager = nil
  55. container.viewContext.shouldDeleteInaccessibleFaults = true
  56. return container
  57. }()
  58. /// Creates and configures a private queue context
  59. private func newTaskContext() -> NSManagedObjectContext {
  60. // Create a private queue context
  61. /// - Tag: newBackgroundContext
  62. let taskContext = persistentContainer.newBackgroundContext()
  63. taskContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
  64. taskContext.undoManager = nil
  65. return taskContext
  66. }
  67. func fetchPersistentHistory() async {
  68. do {
  69. try await fetchPersistentHistoryTransactionsAndChanges()
  70. } catch {
  71. debugPrint("\(error.localizedDescription)")
  72. }
  73. }
  74. private func fetchPersistentHistoryTransactionsAndChanges() async throws {
  75. let taskContext = newTaskContext()
  76. taskContext.name = "persistentHistoryContext"
  77. debugPrint("Start fetching persistent history changes from the store ... \(DebuggingIdentifiers.inProgress)")
  78. try await taskContext.perform {
  79. // Execute the persistent history change since the last transaction
  80. /// - Tag: fetchHistory
  81. let changeRequest = NSPersistentHistoryChangeRequest.fetchHistory(after: self.lastToken)
  82. let historyResult = try taskContext.execute(changeRequest) as? NSPersistentHistoryResult
  83. if let history = historyResult?.result as? [NSPersistentHistoryTransaction], !history.isEmpty {
  84. self.mergePersistentHistoryChanges(from: history)
  85. return
  86. }
  87. }
  88. }
  89. private func mergePersistentHistoryChanges(from history: [NSPersistentHistoryTransaction]) {
  90. debugPrint("Received \(history.count) persistent history transactions")
  91. // Update view context with objectIDs from history change request
  92. /// - Tag: mergeChanges
  93. let viewContext = persistentContainer.viewContext
  94. viewContext.perform {
  95. for transaction in history {
  96. viewContext.mergeChanges(fromContextDidSave: transaction.objectIDNotification())
  97. self.lastToken = transaction.token
  98. }
  99. }
  100. }
  101. // MARK: - Fetch Requests
  102. //
  103. // the first I define here is for background work...I decided to pass a parameter context to the function to execute it on the viewContext if necessary, but for updating the UI I've decided to rather create a second generic fetch function with a completion handler which results are returned on the main thread
  104. //
  105. // first fetch function
  106. // fetch on the thread of the backgroundContext
  107. func fetchEntities<T: NSManagedObject>(
  108. ofType type: T.Type,
  109. predicate: NSPredicate,
  110. key: String,
  111. ascending: Bool,
  112. fetchLimit: Int? = nil,
  113. batchSize: Int? = nil,
  114. propertiesToFetch: [String]? = nil,
  115. callingFunction: String = #function,
  116. callingClass: String = #fileID
  117. ) -> [T] {
  118. let request = NSFetchRequest<T>(entityName: String(describing: type))
  119. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  120. request.predicate = predicate
  121. if let limit = fetchLimit {
  122. request.fetchLimit = limit
  123. }
  124. if let batchSize = batchSize {
  125. request.fetchBatchSize = batchSize
  126. }
  127. if let propertiesTofetch = propertiesToFetch {
  128. request.propertiesToFetch = propertiesTofetch
  129. request.resultType = .managedObjectResultType
  130. } else {
  131. request.resultType = .managedObjectResultType
  132. }
  133. let taskContext = newTaskContext()
  134. taskContext.name = "fetchContext"
  135. taskContext.transactionAuthor = "fetchEntities"
  136. var result: [T]?
  137. /// we need to ensure that the fetch immediately returns a value as long as the whole app does not use the async await pattern, otherwise we could perform this asynchronously with backgroundContext.perform and not block the thread
  138. taskContext.performAndWait {
  139. do {
  140. debugPrint(
  141. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.succeeded) on Thread: \(Thread.current)"
  142. )
  143. result = try taskContext.fetch(request)
  144. } catch let error as NSError {
  145. debugPrint(
  146. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on Thread: \(Thread.current)"
  147. )
  148. }
  149. }
  150. return result ?? []
  151. }
  152. func fetchEntities2<T: NSManagedObject>(
  153. ofType type: T.Type,
  154. onContext context: NSManagedObjectContext,
  155. predicate: NSPredicate,
  156. key: String,
  157. ascending: Bool,
  158. fetchLimit: Int? = nil,
  159. batchSize: Int? = nil,
  160. propertiesToFetch: [String]? = nil,
  161. callingFunction: String = #function,
  162. callingClass: String = #fileID
  163. ) -> [T] {
  164. let request = NSFetchRequest<T>(entityName: String(describing: type))
  165. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  166. request.predicate = predicate
  167. if let limit = fetchLimit {
  168. request.fetchLimit = limit
  169. }
  170. if let batchSize = batchSize {
  171. request.fetchBatchSize = batchSize
  172. }
  173. if let propertiesTofetch = propertiesToFetch {
  174. request.propertiesToFetch = propertiesTofetch
  175. request.resultType = .managedObjectResultType
  176. } else {
  177. request.resultType = .managedObjectResultType
  178. }
  179. context.name = "fetchContext"
  180. context.transactionAuthor = "fetchEntities"
  181. var result: [T]?
  182. /// we need to ensure that the fetch immediately returns a value as long as the whole app does not use the async await pattern, otherwise we could perform this asynchronously with backgroundContext.perform and not block the thread
  183. context.performAndWait {
  184. do {
  185. debugPrint(
  186. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.succeeded) on Thread: \(Thread.current)"
  187. )
  188. result = try context.fetch(request)
  189. } catch let error as NSError {
  190. debugPrint(
  191. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on Thread: \(Thread.current)"
  192. )
  193. }
  194. }
  195. return result ?? []
  196. }
  197. // second fetch function
  198. // fetch and update UI
  199. func fetchEntitiesAndUpdateUI<T: NSManagedObject>(
  200. ofType type: T.Type,
  201. predicate: NSPredicate,
  202. key: String,
  203. ascending: Bool,
  204. fetchLimit: Int? = nil,
  205. batchSize: Int? = nil,
  206. propertiesToFetch: [String]? = nil,
  207. callingFunction: String = #function,
  208. callingClass: String = #fileID,
  209. completion: @escaping ([T]) -> Void
  210. ) {
  211. let request = NSFetchRequest<NSManagedObjectID>(entityName: String(describing: type))
  212. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  213. request.predicate = predicate
  214. request.resultType = .managedObjectIDResultType
  215. if let limit = fetchLimit {
  216. request.fetchLimit = limit
  217. }
  218. if let batchSize = batchSize {
  219. request.fetchBatchSize = batchSize
  220. }
  221. if let propertiesToFetch = propertiesToFetch {
  222. request.propertiesToFetch = propertiesToFetch
  223. }
  224. let taskContext = newTaskContext()
  225. taskContext.name = "fetchContext"
  226. taskContext.transactionAuthor = "fetchEntities"
  227. // perform fetch in the background
  228. //
  229. // the fetch returns a NSManagedObjectID which can be safely passed to the main queue because they are thread safe
  230. taskContext.perform {
  231. var result: [NSManagedObjectID]?
  232. do {
  233. debugPrint(
  234. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.succeeded) on thread \(Thread.current)"
  235. )
  236. result = try taskContext.fetch(request)
  237. } catch let error as NSError {
  238. debugPrint(
  239. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on thread \(Thread.current)"
  240. )
  241. }
  242. // change to the main queue to update UI
  243. DispatchQueue.main.async {
  244. if let result = result {
  245. debugPrint(
  246. "Returning fetch result to main thread in \(callingFunction) from \(callingClass) on thread \(Thread.current)"
  247. )
  248. // Convert NSManagedObjectIDs to objects in the main context
  249. let mainContext = CoreDataStack.shared.persistentContainer.viewContext
  250. let mainContextObjects = result.compactMap { mainContext.object(with: $0) as? T }
  251. completion(mainContextObjects)
  252. } else {
  253. debugPrint("Fetch result is nil in \(callingFunction) from \(callingClass) on thread \(Thread.current)")
  254. completion([])
  255. }
  256. }
  257. }
  258. }
  259. // fetch and only return a NSManagedObjectID
  260. func fetchNSManagedObjectID<T: NSManagedObject>(
  261. ofType type: T.Type,
  262. predicate: NSPredicate,
  263. key: String,
  264. ascending: Bool,
  265. fetchLimit: Int? = nil,
  266. batchSize: Int? = nil,
  267. propertiesToFetch: [String]? = nil,
  268. callingFunction: String = #function,
  269. callingClass: String = #fileID,
  270. completion: @escaping ([NSManagedObjectID]) -> Void
  271. ) {
  272. let request = NSFetchRequest<NSManagedObjectID>(entityName: String(describing: type))
  273. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  274. request.predicate = predicate
  275. request.resultType = .managedObjectIDResultType
  276. if let limit = fetchLimit {
  277. request.fetchLimit = limit
  278. }
  279. if let batchSize = batchSize {
  280. request.fetchBatchSize = batchSize
  281. }
  282. if let propertiesToFetch = propertiesToFetch {
  283. request.propertiesToFetch = propertiesToFetch
  284. }
  285. let taskContext = newTaskContext()
  286. taskContext.name = "fetchContext"
  287. taskContext.transactionAuthor = "fetchEntities"
  288. // Perform fetch in the background
  289. taskContext.perform {
  290. var result: [NSManagedObjectID]?
  291. do {
  292. debugPrint(
  293. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.succeeded) on thread \(Thread.current)"
  294. )
  295. result = try taskContext.fetch(request)
  296. } catch let error as NSError {
  297. debugPrint(
  298. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on thread \(Thread.current)"
  299. )
  300. }
  301. completion(result ?? [])
  302. }
  303. }
  304. // MARK: - Save
  305. //
  306. // takes a context as a parameter to be executed either on the main thread or on a background thread
  307. // save on the thread of the backgroundContext
  308. func saveContext(useViewContext: Bool = false, callingFunction: String = #function, callingClass: String = #fileID) throws {
  309. let contextToUse = useViewContext ? CoreDataStack.shared.persistentContainer.viewContext : newTaskContext()
  310. try contextToUse.performAndWait {
  311. if contextToUse.hasChanges {
  312. do {
  313. try contextToUse.save()
  314. debugPrint(
  315. "Saving to Core Data successful in \(callingFunction) in \(callingClass): \(DebuggingIdentifiers.succeeded)"
  316. )
  317. } catch let error as NSError {
  318. debugPrint(
  319. "Saving to Core Data failed in \(callingFunction) in \(callingClass): \(DebuggingIdentifiers.failed) with error \(error), \(error.userInfo)"
  320. )
  321. throw error
  322. }
  323. }
  324. }
  325. }
  326. // MARK: - Delete
  327. //
  328. /// Synchronously delete entries with specified object IDs
  329. func deleteObject(identifiedBy objectIDs: [NSManagedObjectID]) {
  330. let viewContext = persistentContainer.viewContext
  331. debugPrint("Start deleting data from the store ...\(DebuggingIdentifiers.inProgress)")
  332. viewContext.perform {
  333. objectIDs.forEach { objectID in
  334. let entryToDelete = viewContext.object(with: objectID)
  335. viewContext.delete(entryToDelete)
  336. }
  337. }
  338. debugPrint("Successfully deleted data. \(DebuggingIdentifiers.succeeded)")
  339. }
  340. /// Asynchronously deletes records
  341. // func batchDelete<T: NSManagedObject>(_ objects: [T]) async throws {
  342. // let objectIDs = objects.map(\.objectID)
  343. // let taskContext = newTaskContext()
  344. // // Add name and author to identify source of persistent history changes.
  345. // taskContext.name = "deleteContext"
  346. // taskContext.transactionAuthor = "batchDelete"
  347. // debugPrint("Start deleting data from the store... \(DebuggingIdentifiers.inProgress)")
  348. //
  349. // try await taskContext.perform {
  350. // // Execute the batch delete.
  351. // let batchDeleteRequest = NSBatchDeleteRequest(objectIDs: objectIDs)
  352. // guard let fetchResult = try? taskContext.execute(batchDeleteRequest),
  353. // let batchDeleteResult = fetchResult as? NSBatchDeleteResult,
  354. // let success = batchDeleteResult.result as? Bool, success
  355. // else {
  356. // debugPrint("Failed to execute batch delete request \(DebuggingIdentifiers.failed)")
  357. // throw CoreDataError.batchDeleteError
  358. // }
  359. // }
  360. //
  361. // debugPrint("Successfully deleted data. \(DebuggingIdentifiers.succeeded)")
  362. // }
  363. }