Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa key value observing a key/entry in a dictionary

Is it possible to observe a specific key in a dictionary? If so how can I do it?

like image 390
Justin Meiners Avatar asked Dec 22 '10 01:12

Justin Meiners


People also ask

What is key-value observation?

Key-value observing is a Cocoa programming pattern you use to notify objects about changes to properties of other objects. It's useful for communicating changes between logically separated parts of your app—such as between models and views. You can only use key-value observing with classes that inherit from NSObject .

What is key-value Coding and key-value observing?

KVO and KVC or Key-Value Observing and Key-Value Coding are mechanisms originally built and provided by Objective-C that allows us to locate and interact with the underlying properties of a class that inherits NSObject at runtime.

Can you explain KVO and how it's used on Apple's platforms?

Key-Value Observing, KVO for short, is an important concept of the Cocoa API. It allows objects to be notified when the state of another object changes. That sounds very useful.


1 Answers

Yes (although it only makes sense to be observing an NSMutableDictionary).

@interface Foo : NSObject @end
@implementation Foo 

- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    NSLog(@"observing: -[%@ %@]", object, keyPath);
    NSLog(@"change: %@", change);
}

@end

int main (int argc, const char * argv[]) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    Foo * f = [[Foo alloc] init];

    NSMutableDictionary * d = [NSMutableDictionary dictionary];
    [d addObserver:f forKeyPath:@"foo" options:0 context:NULL];
    [d setObject:@"bar" forKey:@"foo"];
    [d removeObjectForKey:@"foo"];
    [d removeObserver:f forKeyPath:@"foo"];
    [f release];

    [pool drain];
    return 0;
}

Logs:

2010-12-21 17:39:53.758 EmptyFoundation[94589:a0f] observing: -[{
    foo = bar;
} foo]
2010-12-21 17:39:53.764 EmptyFoundation[94589:a0f] change: {
    kind = 1;
}
2010-12-21 17:39:53.765 EmptyFoundation[94589:a0f] observing: -[{
} foo]
2010-12-21 17:39:53.765 EmptyFoundation[94589:a0f] change: {
    kind = 1;
}
like image 99
Dave DeLong Avatar answered Oct 21 '22 15:10

Dave DeLong