KVO Swift: newValue 始终为 nil

KVO Swift: newValue is always nil

有如下例子:

import UIKit

@objc class ViewController: UIViewController {

    @objc dynamic var buggyApple: NSObject?

    var obs: NSKeyValueObservation?

    override func viewDidLoad() {
        super.viewDidLoad()
        obs = observe(\.buggyApple, changeHandler: { (obj, change) in
            print(change)
        })
        buggyApple = NSObject()
        buggyApple = NSObject()
    }
}

我在调试控制台得到了相应的输出:

NSKeyValueObservedChange<Optional<NSObject>>(kind: __C.NSKeyValueChange, newValue: Optional(nil), oldValue: Optional(nil), indexes: nil, isPrior: false)
NSKeyValueObservedChange<Optional<NSObject>>(kind: __C.NSKeyValueChange, newValue: Optional(nil), oldValue: Optional(nil), indexes: nil, isPrior: false)

LLDB 的回调内检查断点上的 ViewController 对象时,我得到以下信息:

(lldb) po obj.buggyApple
▿ Optional<NSObject>
  - some : <NSObject: 0x600000908fa0>

所以,其实新的NSObject已经发送成功了,但是change仍然是引用nil。我的代码有什么问题吗?如何解决?

您需要向 observer 方法的 options 输入参数提供 new 选项以接收 change 中的新值。

obs = observe(\.buggyApple, options: [.new], changeHandler: { (obj, change) in
    print(change)
})