【问题标题】:Is an NSMutableDictionary key-value compliant for every key?NSMutableDictionary 键值对每个键都兼容吗?
【发布时间】:2011-07-28 23:20:15
【问题描述】:

我需要在很多不同的键上设置一些观察者,我不想声明大约 50 个不同的@properties,(就像我已经开始做的那样)所以我想知道 NSDictionary 是否可以为我做这一切?

更新

我想我应该更具体一点,我希望能够为 NSMutableDictionary 中的任意键(NSStrings)设置对象,然后还可以为同一字典中的任意键 registerObserver,无论之前是否设置过该键在那个字典里。 NSMutableDictionary 是否以这种方式“开箱即用”?还是我需要创建一个覆盖 setValue:forKey: 的容器类?

更新 2

我把这个快速测试放在一起,看起来很有希望。在这里使用 SenTestingKit 进行测试。

//My dictionary
NSMutableDictionary * myDict = [[NSMutableDictionary alloc] init];

//An object that does not respond to notifications, and will therefore throw exceptions
NSNumber * notKVOcompliant = [NSNumber numberWithInt:1];

//Adding that object as an observer...
[myDict addObserver:notKVOcompliant forKeyPath:@"five" options:NSKeyValueObservingOptionNew context:nil];

//causing a notification to fire, which causes an exception to throw.
STAssertThrows([myDict setObject:@"something" forKey:@"five"],@"Notification was not sent.");

//A control group, to make sure the exception is because of the specific observed key
STAssertNoThrow([myDict setObject:@"something" forKey:@"six"], @"Control group");

//and lastly a manufactured failure to make sure this test has run
STFail(@"Ensure this test is running");

所以我运行了它,看起来它确实可以开箱即用。 NSNumber 作为观察者必须收到通知,这会导致它抛出无法识别的选择器异常,从而导致 STAssertThrows 通过。

另一个键没有观察者,因此没有效果。

STFail 失败,这意味着测试肯定在运行。

【问题讨论】:

  • @titaniumdeocy - 我在发帖前确实读过这个问题,看起来很相似,但他问的不是同一个问题,他想订阅所有键,就好像它们是一个 NSArray,我想订阅特定的。
  • @bbum 我不敢相信这行不通,所以我试了一下,它确实符合任何 NSString 的键值对。如果不确定,请尽量不要猜测。
  • 不是猜测。旧资料。我会阅读源代码以确保它得到真正的支持。

标签: objective-c nsdictionary key-value-observing


【解决方案1】:

是的,是的。当使用setValue:forKey: 更改键时,一个普通的非子类 NSMutableDictionary 会为订阅的任何 NSString 键提供 KVO 通知

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    • 2022-12-12
    相关资源
    最近更新 更多