Mastering Key-Value Observing (KVO) and Key-Value Coding (KVC) in Swift

A Deep Dive into KVO and KVC Techniques for Modern iOS Development

Vikram Kumar
4 min readNov 25, 2023

Key-Value Observing (KVO) and Key-Value Coding (KVC) are powerful concepts in Swift that enable a more dynamic and flexible approach to handling data in your applications. In this article, we’ll delve into the intricacies of KVO and KVC, exploring their usage, implementation, and providing practical coding examples.

Photo by Sushobhan Badhai on Unsplash

Understanding Key-Value Coding (KVC)

What is KVC?

Key-Value Coding (KVC) is a mechanism provided by Cocoa (and therefore, Swift) that allows you to access an object’s properties indirectly using string identifiers rather than direct method invocations. It enables a concise and dynamic way of working with data.

Basic Usage of KVC:

Let’s consider a simple class:

class Person: NSObject {
@objc dynamic var name: String
@objc dynamic var age: Int

init(name: String, age: Int) {
self.name = name
self.age = age
}
}

With KVC, you can access and set values like this:

let person = Person(name: "John Doe", age: 30)

// Using KVC to get the value
let personName = person.value(forKey: "name") as? String
print("Person's name: \(personName ?? "")")

// Using KVC to set the value
person.setValue("Jane Doe", forKey: "name")
print("Updated name: \(person.name)")

Key Paths in KVC:

Key paths provide a way to traverse through properties or relationships within an object. They are expressed as a string representing the sequence of properties.

// Using key paths
let person = Person(name: "John Doe", age: 30)
let keyPath = \Person.name
let personNameUsingKeyPath = person[keyPath: keyPath]
print("Person's name using key path: \(personNameUsingKeyPath)")

Understanding Key-Value Observing (KVO)

What is KVO?

Key-Value Observing (KVO) allows objects to be notified of changes to specific properties of another object. This is particularly useful for responding to changes in model data and updating the user interface accordingly.

Basic Usage of KVO:

class Observer: NSObject {
var observation: NSKeyValueObservation?

func startObserving(person: Person) {
observation = person.observe(\.name, options: [.new]) { (_, change) in
if let newName = change.newValue as? String {
print("Person's name changed to \(newName)")
}
}
}
}

let person = Person(name: "John Doe", age: 30)
let observer = Observer()
observer.startObserving(person: person)

// Triggering a change to see the observation in action
person.name = "Jane Doe"

In this example, the Observer class observes changes to the name property of a Person object. When the name property changes, the closure within the observe method is executed.

Automatic Key Paths in KVO:

Swift 4 introduced automatic key paths, making KVO more Swift-friendly:

class Observer: NSObject {
var observation: NSKeyValueObservation?

func startObserving(person: Person) {
observation = person.observe(\.name) { (_, change) in
if let newName = change.newValue {
print("Person's name changed to \(newName)")
}
}
}
}

In this example, the key path is automatically inferred from the property being observed.

Practical Example: Using KVO and KVC Together

Let’s create a more comprehensive example by combining KVO and KVC. We’ll observe changes to the age property and use KVC to dynamically access and modify it.

class CombinedObserver: NSObject {
var observation: NSKeyValueObservation?

func startObserving(person: Person) {
observation = person.observe(\.age) { (_, change) in
if let newAge = change.newValue {
print("Person's age changed to \(newAge)")
}
}
}

func updateAgeUsingKVC(person: Person, newAge: Int) {
person.setValue(newAge, forKey: "age")
print("Updated age using KVC: \(person.age)")
}
}

let person = Person(name: "John Doe", age: 30)
let combinedObserver = CombinedObserver()

combinedObserver.startObserving(person: person)
combinedObserver.updateAgeUsingKVC(person: person, newAge: 35)

In this example, the CombinedObserver observes changes to the age property and uses KVC to dynamically update the age.

Interview Questions

Here are some interview questions related to Key-Value Observing (KVO) and Key-Value Coding (KVC) in Swift:

  • What is Key-Value Coding (KVC), and why is it useful in Swift development?
  • How do you use KVC to access and set values in an object?
  • Explain the concept of Key-Value Observing (KVO) in Swift.
  • How do you observe changes to a property using KVO?
  • How are key paths inferred automatically in Swift 4 and later?
  • How would you approach more complex scenarios requiring a combination of KVO and KVC?

Conclusion

Key-Value Observing and Key-Value Coding provide powerful mechanisms for handling data in a dynamic and flexible manner. Understanding how to use KVC for indirect property access and KVO for responding to property changes is crucial for building robust and reactive applications in Swift. By combining these concepts, you can create more dynamic and maintainable code.

Happy Coding!

Thank you for reading until the end. Before you go:

--

--

Vikram Kumar

I am Vikram, a Senior iOS Developer at Matellio Inc. focused on writing clean and efficient code. Complex problem-solver with an analytical and driven mindset.