Checking if a value is changed using KVO in Swift 3

后端 未结 2 1177
闹比i
闹比i 2020-12-14 09:25

I would like to know when a set of properties of a Swift object changes. Previously, I had implemented this in Objective-C, but I\'m having some difficulty converting it to

2条回答
  •  一生所求
    2020-12-14 09:56

    My original 'second attempt' contains a bug that will fail to detect when a value changes to or from nil. The first attempt can actually be fixed once one realizes that all values of 'change' are NSObject:

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        let oldValue: NSObject? = change?[.oldKey] as? NSObject
        let newValue: NSObject? = change?[.newKey] as? NSObject
        if newValue != oldValue {
            edit()
        }
    }
    

    or a more concise version if you prefer:

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if change?[.newKey] as? NSObject != change?[.oldKey] as? NSObject {
            edit()
        }
    }
    

提交回复
热议问题