Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 38 ยท Runtime and Interoperability

Key-Value Coding and Key-Value Observing

Read and write properties by name with Key-Value Coding, use key paths and collection operators, and react to changes with Key-Value Observing, including context, removal rules and pitfalls.

Normally you access a property with dot syntax, which fixes the property name when you compile the code. Sometimes you want to choose the property at runtime: a table column named in a configuration file, a generic form that fills any model, a sort by whatever column the user clicked. Key-Value Coding (KVC) does this by reading and writing properties through their names as strings. Key-Value Observing (KVO) builds on it so that an object can be notified when another object's property changes.

Both rely on the runtime and are the foundation of Cocoa bindings, Core Data and many view-model patterns.

Key-Value Coding

OBJECTIVEC
@interface Person : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic) NSInteger age;
@property (nonatomic, strong) Address *address;
@property (nonatomic, strong) NSArray<Person *> *friends;
@end

Person *p = [[Person alloc] init];
[p setValue:@"Ada" forKey:@"name"];          // calls -setName:
[p setValue:@36 forKey:@"age"];              // NSNumber is unboxed into NSInteger
NSString *name = [p valueForKey:@"name"];    // calls -name
NSNumber *age  = [p valueForKey:@"age"];     // boxed on the way out

For a key foo, KVC looks for -foo (or -isFoo) and -setFoo:; if none exist and accessInstanceVariablesDirectly is YES (the default), it reads or writes the instance variable _foo or foo. An unknown key raises NSUndefinedKeyException, which you can handle in -valueForUndefinedKey: and -setValue:forUndefinedKey:.

Key paths

A key path follows a chain of properties separated by dots:

OBJECTIVEC
[p setValue:@"Berlin" forKeyPath:@"address.city"];
NSString *city = [p valueForKeyPath:@"address.city"];

Collections

valueForKey: on an array returns an array of each element's value:

OBJECTIVEC
NSArray *names = [people valueForKey:@"name"];            // all names
NSArray *ages  = [people valueForKeyPath:@"friends.age"];  // array of arrays

Collection operators compute aggregates:

OBJECTIVEC
NSNumber *avg   = [people valueForKeyPath:@"@avg.age"];
NSNumber *max   = [people valueForKeyPath:@"@max.age"];
NSNumber *total = [people valueForKeyPath:@"@sum.age"];
NSNumber *count = [people valueForKeyPath:@"@count"];
NSArray  *uniq  = [people valueForKeyPath:@"@distinctUnionOfObjects.address.city"];

Dictionaries to models

setValuesForKeysWithDictionary: fills an object from a dictionary, handy for JSON:

OBJECTIVEC
[p setValuesForKeysWithDictionary:@{ @"name": @"Grace", @"age": @45 }];
NSDictionary *snapshot = [p dictionaryWithValuesForKeys:@[@"name", @"age"]];

Override setValue:forUndefinedKey: to ignore keys your class does not have, and always validate data from outside.

KVC as a lookup by name

The stand-in below models KVC: each "class" publishes a table that maps key strings to getter and setter functions, and value_for_key/set_value_for_key use it. An unknown key triggers the "undefined key" path.

C Stand-in: KVC with a property table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Key-Value Observing

KVO lets an object ask to be told when a key path on another object changes, without the observed object writing any notification code.

OBJECTIVEC
static void *kContext = &kContext;

// register
[account addObserver:self
          forKeyPath:@"balance"
             options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
             context:kContext];

// receive
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {
    if (context == kContext) {
        NSLog(@"%@ changed from %@ to %@", keyPath,
              change[NSKeyValueChangeOldKey], change[NSKeyValueChangeNewKey]);
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

// unregister
- (void)dealloc {
    [account removeObserver:self forKeyPath:@"balance" context:kContext];
}

KVO fires automatically when the property is changed through its setter, through setValue:forKey:, or with willChangeValueForKey:/didChangeValueForKey: around a direct ivar write. It works because the runtime creates a dynamic subclass of the observed object's class and overrides the setter to post notifications, then changes the object's isa to it (isa-swizzling).

Rules and pitfalls

  • Always remove the observer before it or the observed object is deallocated, or you get a crash or a console warning. Pair every add with a remove.
  • Use a unique context pointer so you do not intercept a superclass's observations.
  • Removing an observer that was never added throws an exception.
  • Computed properties can announce dependencies with +keyPathsForValuesAffectingValueForKey:.
  • Observing is synchronous: the callback runs on the same thread that made the change.
  • To observe a collection's contents, use mutable proxy accessors (mutableArrayValueForKey:), since changing the array in place is not seen as a property change.
  • Newer code often prefers block-based observeValueForKeyPath: replacements (Swift's observe) or notifications.

An observer list in C

The stand-in below mirrors KVO's contract: a property setter that notifies registered observers with old and new values, and the add/remove discipline.

C Stand-in: a setter that notifies observers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does [p valueForKeyPath:@"address.city"] do?

    A key path follows each property in turn.
  2. 2. What does [people valueForKeyPath:@"@avg.age"] return?

    @avg is a collection operator.
  3. 3. What must you do before an observer is deallocated?

    A dangling observer can crash when the observed object later changes.
  4. 4. How does the runtime implement automatic KVO notification?

    The observed object's isa is swapped to a generated subclass overriding the observed setters.

Summary

  • KVC reads and writes properties by string key or key path; collection operators aggregate.
  • Unknown keys raise exceptions unless you override the undefined-key methods.
  • KVO notifies observers on property changes via a runtime-generated subclass; always unregister observers.
  • Use a unique context and remember that callbacks are synchronous.

Next: Interoperability: C, C++ and Swift