6

I'm having some trouble getting the new KVO syntax right. According to the Apple documentation:

Create an observer for the key path and call the observe(_:options:changeHandler) method. For more information on key paths, see Keys and Key Paths.

class MyObserver: NSObject {
    @objc var objectToObserve: MyObjectToObserve
    var observation: NSKeyValueObservation?

    init(object: MyObjectToObserve) {
        objectToObserve = object
        super.init()

        observation = observe(\.objectToObserve.myDate) { object, change in
            print("Observed a change to \(object.objectToObserve).myDate, updated to: \(object.objectToObserve.myDate)")
        }
    }
}

let observed = MyObjectToObserve()
let observer = MyObserver(object: observed)

observed.updateDate()

I'm initializing my observation like so:

self.observation = self.webView!.observe(\.webView.isLoading, changeHandler: { (webView, observedChange) in
    //code
})

but am getting this error:

enter image description here

Eden
  • 1,782
  • 15
  • 23

2 Answers2

10

Turns out the syntax needs to be like this, using the object Type rather than the object instance name:

self.observation = self.webView!.observe(\WKWebView.isLoading, changeHandler: { (webView, observedChange) in
    //code
})

Misread the documentation ¯\_(ツ)_/¯

pkamb
  • 33,281
  • 23
  • 160
  • 191
Eden
  • 1,782
  • 15
  • 23
3

If you use the \. syntax the root element is the observed object so it's simply

self.observation = self.webView!.observe(\.isLoading, ...

The compiler treats your syntax as webView.webView.isLoading which is obviously not intended.

vadian
  • 274,689
  • 30
  • 353
  • 361
  • You should consider `self.observe(\.webView.isLoading, ...` instead. That is, if `self.webView` changes, you want KVO to automatically stop observing the old web view and start observing the `isLoading` property of the new one. – Ken Thomases Nov 13 '18 at 00:45