2014-02-07 45 views
3

我想使用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; 
} 
+0

对我来说这似乎是一个艰难的。在设置,获取和观察字典中的值时,可能便宜的出路将替代别的东西。 – Merlevede

+0

@Merlevede确实解决了我遇到的问题,但我会认为这是我的最后一招。如果有一种方法可以观察包含点的字典中的键,那将会容易得多。 – derekvanvliet

+3

由于[KVC指南](https://developer.apple.com/library/ios/documentation/cocoa/conceptual/KeyValueCoding/Articles/BasicPrinciples.html#//apple_ref/doc/uid/20002170-183455)非常明确这一点。点用于调用访问器方法。所以没有办法解决你的问题。 – VenoMKO

回答

0

因为它是无法使用的键点你NSDictionary与KVO,你可以把包含点语法的字符串散列化,然后用它作为键。这将提供一个唯一可识别的密钥,同时保留点语法 - 尽管有一些哈希/去哈希开销。

+0

你可以在你的NSDictionary键中有_anything_。甚至不必是字符串(并且我一直使用具有不同密钥的字典)。只有关键/价值观察有问题。 – gnasher729

+0

谢谢我会更新我的答案 – cleverbit