Episode #16

Key Value Observing

14 minutes
Published on May 17, 2012

This video is only available to subscribers. Get access to this video and 573 others.

Key Value Observing (or KVO) is a powerful technique that you can use to be notified when a property changes. In this episode, we'll observe a property on a view to respond when it is updated. In addition, we'll look at the ramifications of KVO on your own classes.

Episode Links

Registering an observer

static void * kBackgroundColorObservationContext = &kBackgroundColorObservationContext;

[self.view addObserver:self
            forKeyPath:@"backgroundColor"
               options:NSKeyValueObservingOptionOld
               context:kBackgroundColorObservationContext];

Observing Changes

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (context == kBackgroundColorObservationContext) {
       /* This change is meant for us */        

        NSLog(@"Key changed from %@ to %@", 
              [change objectForKey:NSKeyValueChangeOldKey],
              self.view.backgroundColor);
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

Cleaning up

- (void)viewDidUnload {
    [super viewDidUnload];
    /* ... other cleanup ... */

    [self.view removeObserver:self forKeyPath:@"backgroundColor"];
}

- (void)dealloc {
    /* ... other cleanup ... */
    [self.view removeObserver:self forKeyPath:@"backgroundColor"];
}

Supporting KVO for other keys

KVO is already supported for your own property accessors, however if you have something custom where and you need to modify values outside of property accessors, you might need to raise the KVO events so others can subscribe.

For example:

- (void)setFullName:(NSString *)newFullName {
  [self willChangeValueForKey:@"firstName"];
  [self willChangeValueForKey:@"lastName"];
  // set ivars from newFullName
  [self didChangeValueForKey:@"lastName"];
  [self didChangeValueForKey:@"firstName"];
}

For more information, read this article on KVO Compliance which covers this and more approaches.