【问题标题】:Cocoa key value observing a key/entry in a dictionaryCocoa 键值观察字典中的键/条目
【发布时间】:2011-05-29 04:09:32
【问题描述】:

是否可以观察字典中的特定键?如果可以,我该怎么做?

【问题讨论】:

  • “观察”是指监控任何变化吗?
  • +1 因为那真的很有用
  • 你试过了吗?我花了大约 2 分钟才这样做......

标签: ios objective-c macos cocoa key-value-observing


【解决方案1】:

是的(尽管只有观察 NSMutableDictionary 才有意义)。

@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;
}

日志:

2010-12-21 17:39:53.758 EmptyFoundation[94589:a0f] observing: -[{
    foo = bar;
} foo]
2010-12-21 17:39:53.764 EmptyFoundation[94589:a0f] change: {
    kind = 1;
}
2010-12-21 17:39:53.765 EmptyFoundation[94589:a0f] observing: -[{
} foo]
2010-12-21 17:39:53.765 EmptyFoundation[94589:a0f] change: {
    kind = 1;
}

【讨论】:

  • 非常重要:"虽然只有观察 NSMutableDictionary 才有意义"。如果您“更改” NSDictionary 中的项目(通过创建新的 NSDictionary),您将丢失前 NSDictionary 中对象的 KVO。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-25
  • 1970-01-01
  • 2014-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多