Skip to content

Commit a65c753

Browse files
author
Bart Jacobs
committed
Save changes when application is terminated or pushed to background
1 parent 1a2aa54 commit a65c753

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

Notes/CoreDataManager.swift

+41
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
//
88

99
import CoreData
10+
import Foundation
1011

1112
final class CoreDataManager {
1213

@@ -18,6 +19,9 @@ final class CoreDataManager {
1819

1920
init(modelName: String) {
2021
self.modelName = modelName
22+
23+
// Setup Notification Handling
24+
setupNotificationHandling()
2125
}
2226

2327
// MARK: - Core Data Stack
@@ -77,4 +81,41 @@ final class CoreDataManager {
7781
return persistentStoreCoordinator
7882
}()
7983

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+
80121
}

0 commit comments

Comments
 (0)