CoreDataObserver.swift 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import CoreData
  2. import Foundation
  3. class CoreDataObserver {
  4. private var entityUpdateHandlers: [String: () -> Void] = [:] // Dictionary to store pairs of entities and handlers
  5. init() {
  6. setupNotification()
  7. }
  8. func registerHandler(for entityName: String, handler: @escaping () -> Void) {
  9. entityUpdateHandlers[entityName] = handler
  10. }
  11. private func setupNotification() {
  12. Foundation.NotificationCenter.default.addObserver(
  13. self,
  14. selector: #selector(contextDidSave(_:)),
  15. name: NSNotification.Name.NSManagedObjectContextDidSave,
  16. object: nil
  17. )
  18. }
  19. @objc private func contextDidSave(_ notification: Notification) {
  20. guard let userInfo = notification.userInfo else { return }
  21. Task {
  22. await processUpdates(userInfo: userInfo)
  23. }
  24. }
  25. private func processUpdates(userInfo: [AnyHashable: Any]) async {
  26. var objects = Set((userInfo[NSInsertedObjectsKey] as? Set<NSManagedObject>) ?? [])
  27. objects.formUnion((userInfo[NSUpdatedObjectsKey] as? Set<NSManagedObject>) ?? [])
  28. objects.formUnion((userInfo[NSDeletedObjectsKey] as? Set<NSManagedObject>) ?? [])
  29. for (entityName, handler) in entityUpdateHandlers {
  30. let entityUpdates = objects.filter { $0.entity.name == entityName }
  31. DispatchQueue.global(qos: .background).async {
  32. if entityUpdates.isNotEmpty {
  33. handler()
  34. }
  35. }
  36. }
  37. }
  38. }