我想使用KVO来观察NSMutableDictionary中值的更改。但是,我发现它不起作用,因为我想要观察的字典中的键包含点。
为包含点的关键路径添加观察者的正确方法是什么?
例如,this question的解决方案可以正常工作:
@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;
}
然而,这不起作用:
@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:@"com.company.foo" options:0 context:NULL];
[d setObject:@"bar" forKey:@"com.company.foo"];
[d removeObjectForKey:@"com.company.foo"];
[d removeObserver:f forKeyPath:@"com.company.foo"];
[f release];
[pool drain];
return 0;
}
答案 0 :(得分:0)
由于无法在带有KVO的NSDictionary
中的键中使用点,您可以改为对包含点语法的字符串进行散列,并将其用于键。这将提供唯一可识别的密钥,同时保留点语法 - 尽管有一些散列/去散列开销。