NSMutableDictionary以nil为值

时间:2013-10-06 20:19:00

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

我在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!");
    }
}

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

我已经在@synchronized块中包含对观察者(本地实例变量)的每次访问,以防万一其他线程正在进行(没有)。

请查看我的代码(BSD许可证)并查看它,并帮助我了解这是怎么回事。如果您愿意的话,我很乐意与您合作编程,我是推特上的@niklassaers

1 个答案:

答案 0 :(得分:4)

你还没有实现哈希。

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

字典正在复制你的密钥对象并存储它 - 当它试图查找原始密钥对象时,它找不到它,因为哈希值不匹配。