我想使用KVO观察对NSMutableDictionary中值的更改。但是,我发现它不起作用,因为我想观察字典中的关键字包含点。键值观察包含点的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;
}
对我来说这似乎是一个艰难的。在设置,获取和观察字典中的值时,可能便宜的出路将替代别的东西。 – Merlevede
@Merlevede确实解决了我遇到的问题,但我会认为这是我的最后一招。如果有一种方法可以观察包含点的字典中的键,那将会容易得多。 – derekvanvliet
由于[KVC指南](https://developer.apple.com/library/ios/documentation/cocoa/conceptual/KeyValueCoding/Articles/BasicPrinciples.html#//apple_ref/doc/uid/20002170-183455)非常明确这一点。点用于调用访问器方法。所以没有办法解决你的问题。 – VenoMKO