Source code for the WriteFreely SwiftUI app for iOS, iPadOS, and macOS
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 

51 rinda
1.8 KiB

  1. import CoreData
  2. #if os(iOS)
  3. import UIKit
  4. #elseif os(macOS)
  5. import AppKit
  6. #endif
  7. class PersistenceManager {
  8. static let persistentContainer: NSPersistentContainer = {
  9. let container = NSPersistentContainer(name: "LocalStorageModel")
  10. container.loadPersistentStores { _, error in
  11. container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
  12. if let error = error {
  13. fatalError("Unresolved error loading persistent store: \(error)")
  14. }
  15. }
  16. return container
  17. }()
  18. init() {
  19. let center = NotificationCenter.default
  20. #if os(iOS)
  21. let notification = UIApplication.willResignActiveNotification
  22. #elseif os(macOS)
  23. let notification = NSApplication.willResignActiveNotification
  24. #endif
  25. // We don't need to worry about removing this observer because we're targeting iOS 9+ / macOS 10.11+; the
  26. // system will clean this up the next time it would be posted to.
  27. // See: https://developer.apple.com/documentation/foundation/notificationcenter/1413994-removeobserver
  28. // And: https://developer.apple.com/documentation/foundation/notificationcenter/1407263-removeobserver
  29. // swiftlint:disable:next discarded_notification_center_observer
  30. center.addObserver(forName: notification, object: nil, queue: nil) { [weak self] _ in
  31. guard let self = self else { return }
  32. self.saveContext()
  33. }
  34. }
  35. func saveContext() {
  36. if PersistenceManager.persistentContainer.viewContext.hasChanges {
  37. do {
  38. try PersistenceManager.persistentContainer.viewContext.save()
  39. } catch {
  40. print("Error saving context: \(error)")
  41. }
  42. }
  43. }
  44. }