Map with int key in objectiveC

10,481

The best option (if you don't want to mess with C++) is using a NSMutableDictionary with NSNumbers as keys. This is easier with the new literal syntax:

NSMutableDictionary *map = [NSMutableDictionary dictionary];
map[@1] = @"A value";
map[@578] = @"Another string";
int key = 310; // doesn't matter where this comes from
map[@(key)] = @"From a variable!";
Share:
10,481
Andrew
Author by

Andrew

Updated on June 04, 2022

Comments

  • Andrew
    Andrew about 2 years

    I need to map integer values to objects in some sort of mutable array. What would be the best way to go about this. The only options I see are to use objectiveC++ ...

    std::map<int, id> theMap;  // if i can use id?
    

    or put the ints into NSString or NSNumber to use as keys for an NSMutableDictionary.

    I am using this for my network class where the client would send some data (the key would be in the payload). Then on read the key would be extracted from the packet, then object in the map would be pulled out to continue the program based on what was received. (I was worried about the client receiving payloads out of order or lost payloads.)

    Which would be the best / fastest approach?