How can I use an integer value as 'key' to set value in NSMutableDictionary?

Ratan picture Ratan · Jan 27, 2011 · Viewed 46.6k times · Source

How can I use an integer value as 'key' to set a float value in NSMutableDictionary ?

Answer

John Parker picture John Parker · Jan 27, 2011

As NSDictionarys are only designed to deal with objects, a simple way to do this is to wrap the integer and float in a NSNumber object. For example:

NSMutableDictionary *testDictionary = [[NSMutableDictionary alloc] init];
[testDictionary setObject:[NSNumber numberWithFloat:1.23f]
                   forKey:[NSNumber numberWithInt:1]];
NSLog(@"Test dictionary: %@", testDictionary);

[testDictionary release];

To extract the relevant value, simply use the appropriate intValue, floatValue, etc. method from the NSNumber class.