KVO Swift:newValue始终为零

时间:2019-06-03 12:57:35

标签: swift key-value-observing objective-c-runtime

具有以下示例:

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)

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

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

因此,实际上,新的NSObject已成功发送,但是change仍是引用nil。我的代码中有任何问题以及如何解决?

1 个答案:

答案 0 :(得分:3)

您需要为Accessing hidden method Landroid/view/MotionEvent;-><init>()V (dark greylist, JNI) 方法的new输入参数提供options选项,以在observer中接收新值。

change