【问题标题】:Key Value Observing a key in an NSMutableDictionary that contains dots?键值观察 NSMutableDictionary 中包含点的键?
【发布时间】: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


【解决方案1】:

由于无法通过 KVO 在 NSDictionary 的键中使用点,因此您可以改为散列包含点语法的字符串,并将其用作键。这将提供一个唯一可识别的密钥,同时保留点语法 - 尽管有一些散列/去散列开销。

【讨论】:

  • 您可以在 NSDictionary 键中包含 anything。甚至不必是字符串(而且我一直使用具有不同键的字典)。只是键/值观察有问题。
猜你喜欢
  • 2012-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多