Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KVO Swift: newValue is always nil

Having the following example:

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()
    }
}

I get the corresponding output in the debug console:

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)

While inspecting the ViewController object on breakpoint inside the callback in the LLDB, I get the following:

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

So, in fact, the new NSObject has been successfully sent, however, the change is still references nil. Is there any problem in my code and how to fix it?

like image 557
Richard Topchii Avatar asked Oct 22 '25 14:10

Richard Topchii


1 Answers

You need to supply the new option to the options input argument of the observer method to receive the new value in change.

obs = observe(\.buggyApple, options: [.new], changeHandler: { (obj, change) in
    print(change)
})
like image 144
Dávid Pásztor Avatar answered Oct 24 '25 06:10

Dávid Pásztor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!