在一个类实例中,我在方法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)")
}
}发布于 2020-08-26 14:08:26
在观察者死亡或调用removeObserver(_:)之前,NotificationCenter将一直向观察者发送通知。
https://stackoverflow.com/questions/63591253
复制相似问题