2013-10-06 34 views
0

我有一個項目https://github.com/niklassaers/NJSNotificationCenter到目前爲止只有兩個單元測試。其中一個運行,其中一個運行60%的時間。時間剩下的40%,這將失敗,因爲我NSMutableValue包含一個零值,儘管我從來沒有把在零值(也不應該說是可能的)NSMutableDictionary與零作爲值

的問題就出現在這裏:

- (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塊中包裝了每個對observers(一個本地實例變量)的訪問權限,以防萬一有其他線程正在進行(沒有)。

請查看我的代碼(BSD許可證)並查看它,並幫助我理解這可能是什麼。如果你願意,我很樂意將這個程序與你配對,我是Twitter上的@niklassaers

+0

你真的實例化一個字典實例嗎? –

+0

我懷疑這段文字:NJSNotificationValue * value = [[NJSNotificationValue alloc] initWithSelector:aSelector]; – yunas

+0

@ColinMorelli:我是,觀察員不是零。如果你看看init方法,它會在那裏實例化。 – niklassaers

回答

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 

字典是複製你的鑰匙對象和存儲 - 當它試圖查找原始密鑰對象,它沒有找到它,因爲哈希值不匹配。

+0

非常感謝你! :-)我沒有注意到那部分文檔,只是它必須符合NSCopying。使用散列函數,我的測試運行良好。 :-) 再次感謝! – niklassaers

相關問題