Back to Basics: Using KVO

One of the things I like most about Apple’s iOS SDK is the consistent and easy-to-use API they provide.  Across all their different frameworks there’s a pattern at work that makes using their classes easy to understand.  This is due in part to the simplicity for configuring those objects.  In most cases you don’t need to call cryptic methods to setup or teardown classes.  If you want to change a label’s font, you just set a property.  If you want to add a new set of tabs to a UITabBarController, you simply have to assign an array of view controllers to the “viewControllers” property and away you go.

This up front simplicity comes at a cost however: somebody had to write code to intercept the setting of those properties and update the view to reflect the changes made.  Fortunately for those developers at Apple, Cocoa and Cocoa Touch makes this simple through the use of Key-Value-Observing (KVO).  If you know how to use it, you can do the same thing in your applications as well.  Read on to see what I do to make implementing KVO in my projects easy and intuitive.

What is Key-Value-Observing?

Key-Value-Observing, or more commonly KVO, is a mechanism by which you can observe changes to keys and their values bound to an object.  It lets you make arbitrary objects aware of changes made to values in other objects that are important to you.  When those values are changed at all, the observeValueForKeyPath:ofObject:change:context: method is invoked on the listener, or “observer”.  In essence, it lets you listen to when people change properties on your object.

You might say “Really? That’s all it does? I can get the same by creating a custom setter!” and you might be right, but there’s several reasons why creating custom setters to handle update logic might be undesirable:

  1. It’s easy to create one or two custom setters, but quite tedious if you have lots of properties you want to observe.
  2. Custom setters only work if you are monitoring properties under your control, but impossible if you want to monitor changes made to other objects you encapsulate.
  3. You have to implement your own retain/release/copy cycles manually, instead of simply using @synthesize.
  4. You have to manually keep track of what the old and new values of a property, if they’re important to you.
  5. Your code looks like dog food.

Using KVO in a class essentially buys you flexibility and easy-to-read code, and with a few general practices can be made easy to read and easy to extend.

Setting up KVO the hard way

Many developers getting started with KVO, myself included, typically start by assigning observers for one or two keyPath properties in either their init or viewDidLoad methods.  Then, within their observeValueForKeyPath:ofObject:change:context: method they will have code to respond to those setting changes.

As an example lets assume we’re creating a UIView subclass that has a UIColor property that controls the display of several subviews.

When that property changes lets make our view update all our sub-views to the appropriate color. We could do this with a custom setter, like so:

For the purposes of this example though, lets utilize KVO for this.

In the initWithFrame: method we add ourselves as an observer of the keyPath “color”, passing in the default options.  We also define a method that Cocoa Touch uses to notify the observer, in this case “self”, when a keyPath has been changed.  This method is invoked for different properties that are changed, so you should always pass the message along to “super” if this method is called for a property you didn’t explicitly add as an observer.

While the above code does look longer than the custom setter equivalent, in the long-run this code is much easier to extend over the life of your class, especially as you add more complex behaviors.

Keeping Track of Your Key Paths

As my experience with KVO improved, so did my techniques for managing my observers, responding to keyPath value changes, and generally keeping my code clean.  One of the things I found was that it is useful to keep a list of the keyPaths you’re observing so that you can conveniently iterate over them programmatically.

To illustrate my point, consider an example where you expose multiple subviews as properties, and when some values change you would like to perform some sort of redraw operation.

As you can see not only would this be impossible to do with custom setters, but we managed to respond to several different property changes using a single block of code.

Additionally, keeping a static NSSet object around with a list of the keys you’re observing is convenient for several reasons:

  1. It lets you easily add your object as an observer of several keyPaths without having to copy/paste code.
  2. Your generated code is tighter because you don’t have to worry about inline strings being littered throughout your class.
  3. If you change the name of a keyPath, it happens in a much more limited area.

There are other advantages, but this is just the tip of the iceberg.

Implementing KVO in a UITableViewCell Subclass

In order to illustrate how to build a more complicated feature using KVO, lets create a UITableViewCell subclass that makes it easy to create a gloss icon in your table cells, just like the iTunes App Store app.  If we’re successful we should be able to create a table cell whose icon looks like the screenshot to the right.

Instead of requiring us to worry about the details of rendering the gloss icon overlay every time we want to display an app icon, lets create a property on our table cell that encapsulates this behavior.  Ideally we should be able to set the app icon’s original image once, and the UITableViewCell imageView.image property should be set to the appropriate content.  We could do this with a custom accessor, but I’d like to show you an easy way to do this with KVO.

You can see from our interface declaration that we’re adding two properties for the icon image itself, and a boolean indicating whether or not we want the gloss effect.  Now lets look at the implementation.

This code may seem complicated, but in the end it is very straight-forward. I’m also introducing a few additional concepts here that I’d like to call out specifically.

Observing Options

KVO allows you to specify different options for when you’re observing a set of keyPaths. It’s a bit-mask, so you can enable multiple options simultaneously.  In this example I’m indicating that I want to be notified of both the old and new values of these properties.  When the icon is changed, the change dictionary supplied to our callback tells us both the old and new values of the property.

Using static strings for keyPaths

This is a pattern I use which helps for simplicity of code, as well as a defensive coding mechanism. By declaring static NSString variables for each keyPath you’re observing, it ensures you won’t accidentally type the wrong keyPath somewhere in your code. It also gives you a single place for defining, or changing, the keyPath you’re interested in observing.

Returning early from the observer callback

In this example I’m returning early in the block, when the keyPath is not in my set of “ObservableKeys”. This makes the callback code cleaner since you eliminate one extra nested “if” block, and helps to prevent mistakes.

Detecting null values in the observer callback

I find it useful to extract values from the change dictionary as early as possible, and then cast those values as needed.

Using private methods for observer callback behaviour

If you’re not careful your observer callback can get quite large.  It’s powerful to be able to have a single point where complex behaviours and patterns can be established between different properties, but you should make sure it doesn’t become overgrown with logic. It’s better to start out by pushing complex logic into private methods, and simply invoke that from within your callback.

Where to go for help

Apple’s own documentation, as always, is a good source of information but it can tend to be a lot to take in.  At this point you should have a basic understanding of how KVO works, and how you can use it in your application.  You can also download the sample application created above at Github.

Once you get started, finding answers to your questions becomes simpler when you’ve gotten the hang of KVO.  Good luck, and happy coding!


About Michael Nachbaur

iOS app developer, livin' the dream. Working from wherever I find myself; Hawaii, Santa Monica, Vancouver, and elsewhere.

8 Responses to “Back to Basics: Using KVO”

  1. James Beith July 30, 2011 2:25 am

    Another great article. I’ve updated one of my projects with some of your tips already.

  2. TJ July 30, 2011 5:17 am

    Many thanks for this. I have been courting KVO for the last month. I keep reading about t but putting off implementing, this looks like enough to remove any ‘good’ reason to postpone any longer.

  3. griotspeak July 30, 2011 1:21 pm

    One concern of mine has been where to remove self as an observer when using ARC. dealloc isn’t quite off limits but it seems like a place to avoid.

    • Michael Nachbaur July 30, 2011 7:21 pm

      Yeah, and I’m not entirely certain that removeObserver:context: is necessary even in a non-ARC case. I’ll figure this out in more detail once I adopt ARC in one of my projects.

      • griotspeak July 31, 2011 12:24 pm

        looks like I misunderstood what ARC means for dealloc.

        dealloc is still the place to handle all of that. we simply don’t call release … at least I get it now. seems weird writing a dealloc without writing release though.

        • Michael Nachbaur August 1, 2011 3:10 pm

          Yeah, lots of things feel weird with ARC. :-)

  4. Chad Seeger August 9, 2011 1:19 pm

    Great read, thanks Michael. I’m a big fan of the guard clause, glad to see it used in your observeValueForKeyPath. Looking forward to your next post!

    • Michael Nachbaur August 13, 2011 5:36 pm

      I didn’t know that pattern had a name; I just thought it made sense, and makes code a lot cleaner. :-)