【问题标题】:NSMutableDictionary with nil as valueNSMutableDictionary 以 nil 为值
【发布时间】:2013-10-06 20:19:00
【问题描述】:

我在https://github.com/niklassaers/NJSNotificationCenter 有一个项目,到目前为止只有两个单元测试。其中一个运行,其中一个运行 60% 的时间。剩下的 40% 的时间,它会失败,因为我的 NSMutableValue 包含一个 nil 值,即使我从来没有输入一个 nil 值(也不应该这样做)

问题出现在这里:

- (void) addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject priority:(NSInteger)priority {
    NJSNotificationKey *key = [[NJSNotificationKey alloc] initWithObserver:observer name:aName object:anObject];
    NSLog(@"Key is: %p", key);
    key.priority = priority;
    NJSNotificationValue *value = [[NJSNotificationValue alloc] initWithSelector:aSelector];
    NSAssert(value, @"Value cannot be nil!");
    @synchronized(observers) {
        observers[key] = value;
        NSLog(@"Key: %p\tValue: %p\t%@", key, value, observers);
        if(observers[key] == nil)
            NSLog(@"This can't be!");
    }
}

我创建一个键,它不是 nil,我创建一个值,它不是 nil,我将它添加到我的字典并从字典中取回它,但现在它是 nil!这对我来说毫无意义。

我已经将所有对观察者的访问(一个本地实例变量)都封装在一个 @synchronized 块中,以防万一有任何其他线程正在进行(没有)。

请查看我的代码(BSD 许可证)并查看它,并帮助我了解这是怎么回事。如果你愿意,我很乐意和你一起做这个程序,我是 Twitter 上的@niklassaers

【问题讨论】:

  • 你真的在实例化一个字典实例吗?
  • 我怀疑这行:NJSNotificationValue *value = [[NJSNotificationValue alloc] initWithSelector:aSelector];
  • @ColinMorelli:我是,观察者不是零。如果您查看 init 方法,它会在那里实例化。
  • @yunas:请告诉我您对此有何怀疑?它不返回 nil,即使在 NSLog 的时候,它仍然不是 nil,即使它在 NSMutableDictionary 观察者中
  • 如果不能,请替换:observers[key] = value;与 [observers setObject:value forKey:key] 并尝试

标签: ios cocoa-touch cocoa unit-testing nsmutabledictionary


【解决方案1】:

你还没有实现哈希。

https://developer.apple.com/library/ios/documentation/cocoa/Conceptual/Collections/Articles/Dictionaries.html#//apple_ref/doc/uid/20000134-SW8

Keys must implement the hash and isEqual: methods because a dictionary
uses a hash table to organize its storage and to quickly access contained
objects

字典正在复制您的键对象并将其存储 - 当它尝试查找原始键对象时,它没有找到它,因为哈希值不匹配。

【讨论】:

  • 非常感谢! :-) 我没有注意到文档的那部分,只是它必须符合 NSCopying。有了哈希函数,我的测试运行良好。 :-) 再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-01
  • 1970-01-01
相关资源
最近更新 更多