【发布时间】:2014-03-05 01:36:35
【问题描述】:
我想使用 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;
}
【问题讨论】:
-
在我看来这是一个艰难的过程。在设置、获取和观察字典中的值时,也许便宜的出路是用其他东西替换点。
-
@Merlevede 确实解决了我遇到的问题,但我认为这是我的最后手段。如果有一种方法可以观察字典中包含点的键,那就容易多了。
-
KVC Guide 对此非常清楚。点用于调用访问器方法。所以没有办法解决你的问题。
标签: ios iphone objective-c cocoa key-value-observing