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,
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.
An NSMutableDictionary
(assuming that you also need to set values in the dictionary after its initialization) works in two ways:
As a traditional dictionary/hashmap in which you set values like this:
[myDictionary setObject: theValue forKey: anyObject];
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:
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With