在方法setUpNotificationHandling
下面调用的类实例内部,。
我只在代码中实例化一次类,而不是在提交数据时实例化。
一旦添加到通知队列,观察者会保持活动状态吗?还是我需要找到一种方法来一次又一次地调用他们
init(modelName: String) {
self.modelName = modelName
setUpNotificationHandling()
}
private func setUpNotificationHandling() {
let notificationCenter = NotificationCenter.default
if #available(iOS 13.0, *) {
notificationCenter.addObserver(self, selector: #selector(saveChanges(_:)), name: UIScene.willDeactivateNotification, object: nil)
} else {
notificationCenter.addObserver(self, selector: #selector(saveChanges(_:)), name: UIApplication.willResignActiveNotification, object: nil)
}
}
@objc func saveChanges(_ notification: Notification) {
saveChanges()
}
private func saveChanges() {
guard self.managedObjectContext.hasChanges else {
return
}
do {
try self.managedObjectContext.save()
}
catch {
print("unable to save moc")
print("(error), (error.localizedDescription)")
}
}
在观察者死亡或调用removeObserver(_:)
之前,NotificationCenter将继续向观察者发送通知。