45

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

Ratan
  • 1,747
  • 2
  • 18
  • 27
  • 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. – Jon Schneider Jan 06 '19 at 04:54

3 Answers3

83

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.

John Parker
  • 54,048
  • 11
  • 129
  • 129
  • 3
    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? – Stan James Oct 25 '15 at 02:36
8

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.

Stan James
  • 2,535
  • 1
  • 28
  • 35
bbum
  • 162,346
  • 23
  • 271
  • 359
  • `NSMapTable` is only available in iOS 6 and later. – Andreas Ley Jun 27 '13 at 14:13
  • 1
    NSMapTable holds weak references, which may or may not be what you want. That is different than NSDictionary, though. – Ian Michael Williams Dec 09 '14 at 01:16
  • `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`. – qix Mar 02 '15 at 08:44
2

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

Then, retrieve it with -integerValue

sidyll
  • 57,726
  • 14
  • 108
  • 151