观察字典中的键/条目的可可键值 [英] 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?
推荐答案
是的(虽然观察一个 NSMutableDictionary
)。
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;
}
日志:
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;
}
这篇关于观察字典中的键/条目的可可键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文