Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C HashMap equivalent

I am trying to convert a piece of Java code which uses a HashMap that contains as a key an object and a value as an object.

private static HashMap<Class<? extends Component>, ComponentType> componentTypes = new HashMap<Class<? extends Component>, ComponentType>();

I've been reading on how to do this with Obj-C but I have not been successful, most people suggest using a NSDictionary, the problem is that they keys need to be strings and I need them as objects. The other option was NSMapTable, however it is not available on iOS. Would someone be able to assist on how I can convert this into an obj-c equivalent?

thanks,

like image 792
Black20 Avatar asked Dec 29 '11 16:12

Black20


3 Answers

The keys for an NSDictionary do not need to be strings. They can be any object that implements NSCopying. If the object is a custom object, however, it needs to produce sane responses to the -hash and -isEqual: messages, but this is the same as using an object in a Java collection so it shouldn't be much of a challenge.

like image 76
Jason Coco Avatar answered Nov 05 '22 13:11

Jason Coco


An NSMutableDictionary (assuming that you also need to set values in the dictionary after its initialization) works in two ways:

  1. As a traditional dictionary/hashmap in which you set values like this:

    [myDictionary setObject: theValue forKey: anyObject];

  2. As an object with KVC-compliant properties that happen to be defined dynamically:

    [myDictionary setValue: theValue forKey: aString];

If the key is an NSString, then the two are interchangeable, with the exception that you can't set an object to nil with setObject:forKey:, but you can pass nil to setValue:forKey:.

like image 17
Monolo Avatar answered Nov 05 '22 14:11

Monolo


You want to use an NSDictionary. You say that

they keys need to be strings and I need them as objects

The keys to an NSDictionary don't need to be strings -- they can be any object that conforms to the NSCopying protocol.

like image 8
mipadi Avatar answered Nov 05 '22 14:11

mipadi