Geek@Paris

Key-Value Observing, Key-Value Coding, Key-Value Bindings

2010-11-26

1, KVO (Key-Value Observing Programming Guide)
KVO is a mechanism to notify observers automatically when the observed object’s value is changed.
Register an observation

- (void)addObserver:(NSObject *)anObserver forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context

Example:

[observedObject addObserver:observer forKeyPath:@"keyPath"];//Register the observation here.

Remove a registered observation

- (void)removeObserver:(NSObject *)anObserver forKeyPath:(NSString *)keyPath

Example:

[observedObject removeObserver:observer forKeyPath:@"keyPath"];//Remember to remove the registration to avoid crashing.

Receiving value changed messages

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
//You will get messages here.
}

2, KVC (Key-Value Coding Programming Guide)
KVC is a mechanism allows application to access an object’s properties by name (or key).
Before KVC:

- (id)tableView:(NSTableView *)tableview
      objectValueForTableColumn:(id)column
                            row:(int)row
{
    ChildObject *child = [childrenArray objectAtIndex:row];
    if ( [[column identifier] isEqualToString:@"name"] ) {
        return [child name];
    }
    if ( [[column identifier] isEqualToString:@"age"] ) {
        return [child age];
    }
    if ( [[column identifier] isEqualToString:@"favoriteColor"] ) {
        // etc...
    }
    // etc...
}

After KVC:

- (id)tableView:(NSTableView *)tableview
      objectValueForTableColumn:(id)column
                            row:(int)row
{
    ChildObject *child = [childrenArray objectAtIndex:row];
    return [child valueForKey:[column identifier]];
}

Be careful, if the application can’t find the key, it will try to call valueForUndefinedKey:, and if the object doesn’t override this method, it will raise an exception called NSUndefinedKeyException.

3, KVB (Cocoa Bindings Programming)
“Cocoa bindings supports multiple ways of viewing your data, and automatically synchronizes views when models change.”

- (void)bind:(NSString *)binding toObject:(id)observableController withKeyPath:(NSString *)keyPath options:(NSDictionary *)options

example:

[self.view bind:@"frame" toObject:anotherView withKeyPath:@"frame" options:nil];

After that, self.view will always have the same frame as anotherView, no need to use NSNotification or any other complicated mechanism.

Author:admin | Categories:Dev | Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *


Clickcha - The One-Click Captcha