[英]Use NSDictionary as other NSDictionary's key
我正在嘗試實現以下結構:
NSMutableDictionary *dict = [@{} mutableCopy];
NSDictionary *key1 = @{@"id_format": @(1), @"date": @"2014-08-01"};
NSDictionary *key2 = @{@"id_format": @(2), @"date": @"2014-08-02"};
// This runs perfect and can be checked in llvm debugger
// data1 & data2 are NSArray that contain several NSDictionary
[dict setObject:data1 forKey:key1];
[dict setObject:data2 forKey:key2];
// Later, if i try to access dict using another key, returns empty NSArray
NSDictionary *testKey = @{@"id_format": @(1), @"date": @"2014-08-01"}; // Note it's equal to "key1"
for(NSDictionary *dictData in dict[testKey]){
// dictData is empty NSArray
}
// OR
for(NSDictionary *dictData in [dict objectForKey:testKey]){
// dictData is empty NSArray
}
因此,問題是是否可以使用NSDictionary作為密鑰。
如果對象符合NSCopying
,則可以用作鍵,並且應實現hash
和isEqual:
以按值而不是按標識進行比較。
字典遵循返回[self count]
作為hash
的數組約定。 因此,這是一個非常糟糕的哈希,但在技術上是有效的。 這意味着您的外部字典最終將完成實際上是線性搜索的工作,但是它將起作用。
字典實現並正確響應isEqual:
他們還實現了NSCopying
。
因此,您可以將字典用作字典鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.