Initialize NSMutableDictionary

Sibir picture Sibir · Aug 18, 2014 · Viewed 20.2k times · Source

I am developing an iOS application in which I want to use an NSMutableDictionary. Basically what I am doing is converting java code to objectiveC.

So in java I have something like this:

Map<String, ClassA> dict1 = new HashMap<>();
Map<Integer,Character> dict2 = new HashMap<>();
Map<Integer, Map<String,String>> dict3 = new HashMap<>();

Can someone please guide me as what would be the Obj-C equivalent code for the above three lines using NSMutableDictionary and also how can I set and get the pairs in/from the dictionaries.

Answer

trojanfoe picture trojanfoe · Aug 18, 2014

The Objective-C collection classes are not strongly typed so all three dictionaries would be created using:

NSMutableDictionary *dictX = [NSMutableDictionary new];

In order to populate the dictionary use [NSMutableDictionary setObject:forKey:]:

[dict1 setObject:classAInstance
          forKey:@"key1"];
[dict2 setObject:[NSString stringWithFormat:@"%c", character]
          forKey:@(1)];
[dict3 setObject:@{ @"innerKey" : @"innerValue" }
          forKey:@(2)];

etc.