15
可以观察字典中的特定键吗?如果是这样,我该怎么做?观察字典中的键/条目的可可键值
可以观察字典中的特定键吗?如果是这样,我该怎么做?观察字典中的键/条目的可可键值
是的(尽管只有在观察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;
}
通过 “观察” 你的意思是监控任何变化? – 2010-12-22 01:27:43
+1因为那真的很有用 – 2010-12-22 01:28:48