7
7
//
8
8
9
9
import CoreData
10
+ import Foundation
10
11
11
12
final class CoreDataManager {
12
13
@@ -18,6 +19,9 @@ final class CoreDataManager {
18
19
19
20
init ( modelName: String ) {
20
21
self . modelName = modelName
22
+
23
+ // Setup Notification Handling
24
+ setupNotificationHandling ( )
21
25
}
22
26
23
27
// MARK: - Core Data Stack
@@ -77,4 +81,41 @@ final class CoreDataManager {
77
81
return persistentStoreCoordinator
78
82
} ( )
79
83
84
+ // MARK: - Notification Handling
85
+
86
+ @objc func saveChanges( _ notification: NSNotification ) {
87
+ managedObjectContext. perform {
88
+ do {
89
+ if self . managedObjectContext. hasChanges {
90
+ try self . managedObjectContext. save ( )
91
+ }
92
+ } catch {
93
+ let saveError = error as NSError
94
+ print ( " Unable to Save Changes of Managed Object Context " )
95
+ print ( " \( saveError) , \( saveError. localizedDescription) " )
96
+ }
97
+
98
+ self . privateManagedObjectContext. perform {
99
+ do {
100
+ if self . privateManagedObjectContext. hasChanges {
101
+ try self . privateManagedObjectContext. save ( )
102
+ }
103
+ } catch {
104
+ let saveError = error as NSError
105
+ print ( " Unable to Save Changes of Private Managed Object Context " )
106
+ print ( " \( saveError) , \( saveError. localizedDescription) " )
107
+ }
108
+ }
109
+
110
+ }
111
+ }
112
+
113
+ // MARK: - Helper Methods
114
+
115
+ private func setupNotificationHandling( ) {
116
+ let notificationCenter = NotificationCenter . default
117
+ notificationCenter. addObserver ( self , selector: #selector( CoreDataManager . saveChanges ( _: ) ) , name: Notification . Name. UIApplicationWillTerminate, object: nil )
118
+ notificationCenter. addObserver ( self , selector: #selector( CoreDataManager . saveChanges ( _: ) ) , name: Notification . Name. UIApplicationDidEnterBackground, object: nil )
119
+ }
120
+
80
121
}
0 commit comments