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

47,199

Solution 1

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.

Solution 2

You can use NSMapTable as it supports integer keys and/or values directly. No need to box/unbox through NSNumber, but it is also slightly more difficult to set up and use.

Solution 3

It needs to be an object, so use [NSNumber numberWithInt:myInteger] instead.

Then, retrieve it with -integerValue

Share:
47,199

Related videos on Youtube

Ratan
Author by

Ratan

I am passionate about mobile app development.

Updated on October 25, 2020

Comments

  • Ratan
    Ratan over 3 years

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

    • deniz
      deniz over 5 years
      As a potential aid to Google searchers: XCode will give the error Expected method to write array element not found on object of type 'NSMutableDictionary * on an attempt to use a raw int or an NSInteger as an NSMutableDictionary key.
  • John Parker
    John Parker about 13 years
    The integerValue method returns an NSInteger object, not an int. :-)
  • sidyll
    sidyll about 13 years
    Ouch, that should be -intValue. Thanks middaparka
  • EmptyStack
    EmptyStack about 13 years
    @middaparka: NSInteger is not an object.
  • sidyll
    sidyll about 13 years
    @Simon yes haha, but anyway I decided to point -intValue because I think the OP needs the primitive.
  • John Parker
    John Parker about 13 years
    @Simon Ah.. yes. It's a foundation data type. My bad. (Feel free to ignore the above.) :-)
  • Andreas Ley
    Andreas Ley almost 11 years
    NSMapTable is only available in iOS 6 and later.
  • Ian Michael Williams
    Ian Michael Williams over 9 years
    NSMapTable holds weak references, which may or may not be what you want. That is different than NSDictionary, though.
  • qix
    qix about 9 years
    NSMapInsert isn't available on iOS. Is there a better way to set an integer value other than something like this: [map setObject:(__bridge id)((void *)myInt) forKey:myKey];? I'm assuming the valueOptions were set to NSPointerFunctionsIntegerPersonality | NSPointerFunctionsOpaqueMemory.
  • Thinker
    Thinker over 8 years
    It's telling me that the key must be NSString*, and searching through NSKeyValueCoding.h it looks like all the methods expect strings. Has something changed in the SDK?