Cocoa key value observing a key/entry in a dictionary

女生的网名这么多〃 提交于 2019-12-03 23:16:38

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!