Is it possible to observe a specific key in a dictionary? If so how can I do it?
Asked
Active
Viewed 5,087 times
16
-
By "observe" do you mean monitor for any changes? – Evan Mulawski Dec 22 '10 at 01:27
-
+1 because that would be really useful – Alec Sloman Dec 22 '10 at 01:28
-
Did you try it? It took me about 2 minutes to do so... – Dave DeLong Dec 22 '10 at 01:39
1 Answers
19
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;
}

Dave DeLong
- 242,470
- 58
- 448
- 498
-
4Very important: *"although it only makes sense to be observing an NSMutableDictionary"*. If you "change" the items in an NSDictionary (by creating a new NSDictionary) you'll lose the KVO on the objects in the former NSDictionary. – ck_ Mar 21 '13 at 20:46