Search Your Question

What is KVO?

Key-value observing is the ability for Swift to attach code to variables, so that whenever the variable is changed the code runs. It’s similar to property observers (willSet and didSet ), except KVO is for adding observers outside of the type definition.


KVO isn’t terribly nice in pure Swift code, because it relies on the Objective-C runtime – you need to use @objc classes that inherit from NSObject, then mark each of your properties with @objc dynamic.


For example, we could create a Car class like this:


@objc class Car: NSObject {

    @objc dynamic var name = "BMW"

}


let bmw= Car()

You could then observe that user’s name changing like this:


bmw.observe(\Car.name, options: .new) { car, change in

    print("I'm now called \(car.name)")

}

That asks BMW to watch for new values coming in, then prints the person’s name as soon as the new value is set.


To try it out, just change the car's name to something else:


bmw.name = "Mercedese"

That will print “I’m now called Mercedese.”


Although KVO is unpleasant in pure Swift code, it’s better when working with Apple’s own APIs – they are all automatically both @objc and dynamic because they are written in Objective-C.


However, one warning: even though large parts of UIKit might work with KVO, this is a coincidence rather than a promise – Apple makes no guarantees about UIKit remaining KVO-compatible in the future.

No comments:

Post a Comment

Thanks