Swift: Working with Key-Value Observing

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
May 24, 2024
Working with Key-Value Observing in Swift

Working with Key-Value Observing in Swift

Key-Value Observing (KVO) is a mechanism in Swift that allows an object to observe changes to a property or attribute of another object. This is particularly useful in scenarios where you need to be notified when a certain property of an object changes, without having to explicitly check for changes yourself.

In order to use KVO in Swift, you first need to mark the property you want to observe with the @objc dynamic attribute. This tells Swift that this property can be observed using KVO.

Here's an example of how you can work with KVO in Swift:

class Person: NSObject {
    @objc dynamic var name: String
    
    init(name: String) {
        self.name = name
    }
}

class Observer: NSObject {
    var person: Person

    init(person: Person) {
        self.person = person
        super.init()

        person.addObserver(self, forKeyPath: "name", options: .new, context: nil)
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "name" {
            if let newName = change?[.newKey] as? String {
                print("Name changed to: \(newName)")
            }
        }
    }
}

let john = Person(name: "John")
let observer = Observer(person: john)

john.name = "Jane" // This will trigger the observer to print the new name}

In this example, we have a Person class with a name property that is marked as @objc dynamic. We also have an Observer class that observes changes to the name property of a Person instance.

When we create a Person instance and change the name, the observer will be notified of the change and print out the new name.