当我的上下文保存更改时,我希望能够看到哪些对象已更新,并且这些对象的确切值已更新。
我知道当发出NSManagedObjectContextObjectsDidChange
通知时,我可以查看changedValues()
中每个对象的notification.userInfo
。我希望能够做同样的事情,但是当发出NSManagedObjectContextDidSave
通知时。
如果这不可能,那么在这种情况下的最佳做法是什么?
在上下文更改时依靠changedValues()
的问题是我不确定这些更改是否会保存,因此感觉像是一个脆弱的解决方案。
这是我的代码:
class AppModelController {
init() {
NotificationCenter.default.addObserver(self,
selector: #selector(backgroundContextDidSave(_:)),
name: NSNotification.Name.NSManagedObjectContextDidSave,
object: backgroundContext)
NotificationCenter.default.addObserver(self,
selector: #selector(backgroundContextDidChange(_:)),
name: NSNotification.Name.NSManagedObjectContextObjectsDidChange,
object: backgroundContext)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
private lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "Foo")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
private lazy var backgroundContext: NSManagedObjectContext = {
let context = persistentContainer.newBackgroundContext()
return context
}()
@objc func backgroundContextDidChange(_ notification: Notification) {
guard let userInfo = notification.userInfo else {
return
}
if let updatedObjects = userInfo[NSUpdatedObjectsKey] as? Set<NSManagedObject>, !updatedObjects.isEmpty {
// changedValues() will be empty for every object, even though there are updated objects
for updatedObject in updatedObjects {
print("objectID: \(updatedObject.objectID), changedValues: \(updatedObject.changedValues())")
}
}
}
@objc func backgroundContextDidSave(_ notification: Notification) {
guard let userInfo = notification.userInfo else {
return
}
if let updatedObjects = userInfo[NSUpdatedObjectsKey] as? Set<NSManagedObject>, !updatedObjects.isEmpty {
// Will print changed values
for updatedObject in updatedObjects {
print("objectID: \(updatedObject.objectID), changedValues: \(updatedObject.changedValues())")
}
}
}
}