核心数据:等效于NSManagedObjectContextDidSave中的changedValues()

时间:2019-02-13 13:46:53

标签: ios core-data

当我的上下文保存更改时,我希望能够看到哪些对象已更新,并且这些对象的确切值已更新。

我知道当发出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())")
            }
        }
    }
}

0 个答案:

没有答案