CoreDataStack.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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. /// ensure that the background contexts stay in sync with the main context
  64. taskContext.automaticallyMergesChangesFromParent = true
  65. taskContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
  66. taskContext.undoManager = nil
  67. return taskContext
  68. }
  69. func fetchPersistentHistory() async {
  70. do {
  71. try await fetchPersistentHistoryTransactionsAndChanges()
  72. } catch {
  73. debugPrint("\(error.localizedDescription)")
  74. }
  75. }
  76. private func fetchPersistentHistoryTransactionsAndChanges() async throws {
  77. let taskContext = newTaskContext()
  78. taskContext.name = "persistentHistoryContext"
  79. debugPrint("Start fetching persistent history changes from the store ... \(DebuggingIdentifiers.inProgress)")
  80. try await taskContext.perform {
  81. // Execute the persistent history change since the last transaction
  82. /// - Tag: fetchHistory
  83. let changeRequest = NSPersistentHistoryChangeRequest.fetchHistory(after: self.lastToken)
  84. let historyResult = try taskContext.execute(changeRequest) as? NSPersistentHistoryResult
  85. if let history = historyResult?.result as? [NSPersistentHistoryTransaction], !history.isEmpty {
  86. self.mergePersistentHistoryChanges(from: history)
  87. return
  88. }
  89. }
  90. }
  91. private func mergePersistentHistoryChanges(from history: [NSPersistentHistoryTransaction]) {
  92. debugPrint("Received \(history.count) persistent history transactions")
  93. // Update view context with objectIDs from history change request
  94. /// - Tag: mergeChanges
  95. let viewContext = persistentContainer.viewContext
  96. viewContext.perform {
  97. for transaction in history {
  98. viewContext.mergeChanges(fromContextDidSave: transaction.objectIDNotification())
  99. self.lastToken = transaction.token
  100. }
  101. }
  102. }
  103. // MARK: - Fetch Requests
  104. //
  105. // 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
  106. //
  107. // first fetch function
  108. // fetch on the thread of the backgroundContext
  109. func fetchEntities<T: NSManagedObject>(
  110. ofType type: T.Type,
  111. predicate: NSPredicate,
  112. key: String,
  113. ascending: Bool,
  114. fetchLimit: Int? = nil,
  115. batchSize: Int? = nil,
  116. propertiesToFetch: [String]? = nil,
  117. callingFunction: String = #function,
  118. callingClass: String = #fileID
  119. ) -> [T] {
  120. let request = NSFetchRequest<T>(entityName: String(describing: type))
  121. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  122. request.predicate = predicate
  123. if let limit = fetchLimit {
  124. request.fetchLimit = limit
  125. }
  126. if let batchSize = batchSize {
  127. request.fetchBatchSize = batchSize
  128. }
  129. if let propertiesTofetch = propertiesToFetch {
  130. request.propertiesToFetch = propertiesTofetch
  131. request.resultType = .managedObjectResultType
  132. } else {
  133. request.resultType = .managedObjectResultType
  134. }
  135. let taskContext = newTaskContext()
  136. taskContext.name = "fetchContext"
  137. taskContext.transactionAuthor = "fetchEntities"
  138. var result: [T]?
  139. /// 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
  140. taskContext.performAndWait {
  141. do {
  142. debugPrint(
  143. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.succeeded) on Thread: \(Thread.current)"
  144. )
  145. result = try taskContext.fetch(request)
  146. } catch let error as NSError {
  147. debugPrint(
  148. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on Thread: \(Thread.current)"
  149. )
  150. }
  151. }
  152. return result ?? []
  153. }
  154. func fetchEntities2<T: NSManagedObject>(
  155. ofType type: T.Type,
  156. onContext context: NSManagedObjectContext,
  157. predicate: NSPredicate,
  158. key: String,
  159. ascending: Bool,
  160. fetchLimit: Int? = nil,
  161. batchSize: Int? = nil,
  162. propertiesToFetch: [String]? = nil,
  163. callingFunction: String = #function,
  164. callingClass: String = #fileID
  165. ) -> [T] {
  166. let request = NSFetchRequest<T>(entityName: String(describing: type))
  167. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  168. request.predicate = predicate
  169. if let limit = fetchLimit {
  170. request.fetchLimit = limit
  171. }
  172. if let batchSize = batchSize {
  173. request.fetchBatchSize = batchSize
  174. }
  175. if let propertiesTofetch = propertiesToFetch {
  176. request.propertiesToFetch = propertiesTofetch
  177. request.resultType = .managedObjectResultType
  178. } else {
  179. request.resultType = .managedObjectResultType
  180. }
  181. context.name = "fetchContext"
  182. context.transactionAuthor = "fetchEntities"
  183. var result: [T]?
  184. /// 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
  185. context.performAndWait {
  186. do {
  187. debugPrint(
  188. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.succeeded) on Thread: \(Thread.current)"
  189. )
  190. result = try context.fetch(request)
  191. } catch let error as NSError {
  192. debugPrint(
  193. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on Thread: \(Thread.current)"
  194. )
  195. }
  196. }
  197. return result ?? []
  198. }
  199. // second fetch function
  200. // fetch and update UI
  201. func fetchEntitiesAndUpdateUI<T: NSManagedObject>(
  202. ofType type: T.Type,
  203. predicate: NSPredicate,
  204. key: String,
  205. ascending: Bool,
  206. fetchLimit: Int? = nil,
  207. batchSize: Int? = nil,
  208. propertiesToFetch: [String]? = nil,
  209. callingFunction: String = #function,
  210. callingClass: String = #fileID,
  211. completion: @escaping ([T]) -> Void
  212. ) {
  213. let request = NSFetchRequest<NSManagedObjectID>(entityName: String(describing: type))
  214. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  215. request.predicate = predicate
  216. request.resultType = .managedObjectIDResultType
  217. if let limit = fetchLimit {
  218. request.fetchLimit = limit
  219. }
  220. if let batchSize = batchSize {
  221. request.fetchBatchSize = batchSize
  222. }
  223. if let propertiesToFetch = propertiesToFetch {
  224. request.propertiesToFetch = propertiesToFetch
  225. }
  226. let taskContext = newTaskContext()
  227. taskContext.name = "fetchContext"
  228. taskContext.transactionAuthor = "fetchEntities"
  229. // perform fetch in the background
  230. //
  231. // the fetch returns a NSManagedObjectID which can be safely passed to the main queue because they are thread safe
  232. taskContext.perform {
  233. var result: [NSManagedObjectID]?
  234. do {
  235. debugPrint(
  236. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.succeeded) on thread \(Thread.current)"
  237. )
  238. result = try taskContext.fetch(request)
  239. } catch let error as NSError {
  240. debugPrint(
  241. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on thread \(Thread.current)"
  242. )
  243. }
  244. // change to the main queue to update UI
  245. DispatchQueue.main.async {
  246. if let result = result {
  247. debugPrint(
  248. "Returning fetch result to main thread in \(callingFunction) from \(callingClass) on thread \(Thread.current)"
  249. )
  250. // Convert NSManagedObjectIDs to objects in the main context
  251. let mainContext = CoreDataStack.shared.persistentContainer.viewContext
  252. let mainContextObjects = result.compactMap { mainContext.object(with: $0) as? T }
  253. completion(mainContextObjects)
  254. } else {
  255. debugPrint("Fetch result is nil in \(callingFunction) from \(callingClass) on thread \(Thread.current)")
  256. completion([])
  257. }
  258. }
  259. }
  260. }
  261. // fetch and only return a NSManagedObjectID
  262. func fetchNSManagedObjectID<T: NSManagedObject>(
  263. ofType type: T.Type,
  264. predicate: NSPredicate,
  265. key: String,
  266. ascending: Bool,
  267. fetchLimit: Int? = nil,
  268. batchSize: Int? = nil,
  269. propertiesToFetch: [String]? = nil,
  270. callingFunction: String = #function,
  271. callingClass: String = #fileID,
  272. completion: @escaping ([NSManagedObjectID]) -> Void
  273. ) {
  274. let request = NSFetchRequest<NSManagedObjectID>(entityName: String(describing: type))
  275. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  276. request.predicate = predicate
  277. request.resultType = .managedObjectIDResultType
  278. if let limit = fetchLimit {
  279. request.fetchLimit = limit
  280. }
  281. if let batchSize = batchSize {
  282. request.fetchBatchSize = batchSize
  283. }
  284. if let propertiesToFetch = propertiesToFetch {
  285. request.propertiesToFetch = propertiesToFetch
  286. }
  287. let taskContext = newTaskContext()
  288. taskContext.name = "fetchContext"
  289. taskContext.transactionAuthor = "fetchEntities"
  290. // Perform fetch in the background
  291. taskContext.perform {
  292. var result: [NSManagedObjectID]?
  293. do {
  294. debugPrint(
  295. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.succeeded) on thread \(Thread.current)"
  296. )
  297. result = try taskContext.fetch(request)
  298. } catch let error as NSError {
  299. debugPrint(
  300. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on thread \(Thread.current)"
  301. )
  302. }
  303. completion(result ?? [])
  304. }
  305. }
  306. // MARK: - Save
  307. //
  308. // takes a context as a parameter to be executed either on the main thread or on a background thread
  309. // save on the thread of the backgroundContext
  310. func saveContext(useViewContext: Bool = false, callingFunction: String = #function, callingClass: String = #fileID) throws {
  311. let contextToUse = useViewContext ? CoreDataStack.shared.persistentContainer.viewContext : newTaskContext()
  312. try contextToUse.performAndWait {
  313. if contextToUse.hasChanges {
  314. do {
  315. try contextToUse.save()
  316. debugPrint(
  317. "Saving to Core Data successful in \(callingFunction) in \(callingClass): \(DebuggingIdentifiers.succeeded)"
  318. )
  319. } catch let error as NSError {
  320. debugPrint(
  321. "Saving to Core Data failed in \(callingFunction) in \(callingClass): \(DebuggingIdentifiers.failed) with error \(error), \(error.userInfo)"
  322. )
  323. throw error
  324. }
  325. }
  326. }
  327. }
  328. // MARK: - Delete
  329. //
  330. /// Synchronously delete entries with specified object IDs
  331. func deleteObject(identifiedBy objectIDs: [NSManagedObjectID]) {
  332. let viewContext = persistentContainer.viewContext
  333. debugPrint("Start deleting data from the store ...\(DebuggingIdentifiers.inProgress)")
  334. viewContext.perform {
  335. objectIDs.forEach { objectID in
  336. let entryToDelete = viewContext.object(with: objectID)
  337. viewContext.delete(entryToDelete)
  338. }
  339. }
  340. debugPrint("Successfully deleted data. \(DebuggingIdentifiers.succeeded)")
  341. }
  342. /// Asynchronously deletes records
  343. // func batchDelete<T: NSManagedObject>(_ objects: [T]) async throws {
  344. // let objectIDs = objects.map(\.objectID)
  345. // let taskContext = newTaskContext()
  346. // // Add name and author to identify source of persistent history changes.
  347. // taskContext.name = "deleteContext"
  348. // taskContext.transactionAuthor = "batchDelete"
  349. // debugPrint("Start deleting data from the store... \(DebuggingIdentifiers.inProgress)")
  350. //
  351. // try await taskContext.perform {
  352. // // Execute the batch delete.
  353. // let batchDeleteRequest = NSBatchDeleteRequest(objectIDs: objectIDs)
  354. // guard let fetchResult = try? taskContext.execute(batchDeleteRequest),
  355. // let batchDeleteResult = fetchResult as? NSBatchDeleteResult,
  356. // let success = batchDeleteResult.result as? Bool, success
  357. // else {
  358. // debugPrint("Failed to execute batch delete request \(DebuggingIdentifiers.failed)")
  359. // throw CoreDataError.batchDeleteError
  360. // }
  361. // }
  362. //
  363. // debugPrint("Successfully deleted data. \(DebuggingIdentifiers.succeeded)")
  364. // }
  365. }