Question

I've build some code that makes an auxiliary dictionary to store the keys of the main dictionary. So I can get a key for a value. To make them unique, in case of two or more identical values, I store the IDs of the dictionary objects as keys and their keys as the objects.

But when two objects have the same value, they also have the same ID. Therefore I cannot retrieve two different keys:

NSDictionary *myDict = @{@"key1": @"obj1", @"key2": @"obj1", @"key3" : @"x"};
NSLog(@"%p",[myDict objectForKey:@"key1"]);
NSLog(@"%p",[myDict objectForKey:@"key2"]);

Output:

2013-03-06 02:03:28.740 DictTest[2855:303] 0x1000028e8
2013-03-06 02:03:28.741 DictTest[2855:303] 0x1000028e8

How can I prevent this?

Was it helpful?

Solution

To answer my own question: Its not an issue of the dictionaries, but of the string literals. @"obj1" always gives the same ID. To solve this problem, I have to setup the dictionary by:

NSDictionary *myDict = @{@"key1": [NSMutableString stringWithFormat:@"%@",@"obj1"], @"key2": [NSMutableString stringWithFormat:@"%@",@"obj1"], @"key3" : @"x"};

Note that "NSMutableString"! You will need mutable objects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top