[ACCEPTED]-Using an int as an NSDictionary key?-ios

Accepted answer
Score: 16

If you are using numbers as strings for 6 dictionary keys, you should turn the int into 5 a NSString or NSNumber to use it as a dictionary key. Here's 4 how to do it for a string:

  NSString *key = [NSString stringWithFormat:@"%d", myInteger];

As @Hughes BR 3 mentions in a comment, the requirement for 2 the key object is that it must conform to 1 the NSCopying protocol.

Score: 6

I use NSNumbers without problems, but must 4 avoid the usual setObject: forKey: or setValue: forKey: methods. That would 3 create a warning.

No warning, however, is 2 created (and the code works as intended) with

NSMutableDictionary *myDict = [[NSMutableDictionary alloc] init];
NSNumber *key = @1;
id *myObject  = [your code here];
myDict[key]   = myObject;

Retrieval 1 is straightforward:

myObject = myDict[key];

More Related questions