Use NSDictionary as other NSDictionary's key

i'm trying to achieve the following structure:

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
}

So the question is if is there possible to use NSDictionary as key, or not.

Upvotes: 0

Views: 131

Answers (1)

Tommy
Tommy

Reputation: 100652

An object can be used as a key if it conforms to NSCopying, and should implement hash and isEqual: to compare by value rather than by identity.

Dictionaries follow the array convention of returning [self count] for hash. So it's a pretty bad hash but it's technically valid. It means your outer dictionary will end up doing what is effectively a linear search but it'll work.

Dictionaries implement and correctly respond to isEqual:. They also implement NSCopying.

Therefore you can use a dictionary as a dictionary key.

Upvotes: 4

Related Questions