(Translated from my Chinese blog post)
Using custom objects as dictionary keys is very simple in Java. But in Objective-C, you have to do many things to achieve the goal.
In my previous post, I already discussed one possible solution. I even read the source code of OPENSTEP to figure out why it is the case. But that solution is a bit complicated. You need to implement NSCopying, and override equal
and hash
. Today, I found another solution by using NSValue, which tremendously simplifies the code.
Example code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
NSObject *obj1 = [NSObject new]; NSObject *obj2 = [NSObject new]; NSObject *obj3 = [NSObject new]; NSObject *obj4 = [NSObject new]; NSMutableDictionary *dict = [NSMutableDictionary new]; [dict setObject:@"value1" forKey:[NSValue valueWithNonretainedObject:obj1]]; [dict setObject:@"value2" forKey:[NSValue valueWithNonretainedObject:obj2]]; [dict setObject:@"value3" forKey:[NSValue valueWithNonretainedObject:obj3]]; [dict setObject:@"value4" forKey:[NSValue valueWithNonretainedObject:obj4]]; NSString *v = dict[[NSValue valueWithNonretainedObject:obj4]]; NSLog(@"%@",v); v = dict[[NSValue valueWithNonretainedObject:obj3]]; NSLog(@"%@",v); v = dict[[NSValue valueWithNonretainedObject:obj2]]; NSLog(@"%@",v); v = dict[[NSValue valueWithNonretainedObject:obj1]]; NSLog(@"%@",v); |
References:
http://stackoverflow.com/questions/11532306/using-an-object-as-key-for-nsdictionary
http://nshipster.com/nsvalue/
No Comments