Initialize NSMutableDictionary
I am developing an iOS app that I want to use NSMutableDictionary
. Basically what I am doing is converting Java code to objectC.
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 anyone please guide me as what would be the equivalent Obj-C code for the above three lines using NSMutableDictionary
as well as how can I set and get pairs to / from dictionaries.
source to share
The Objective-C collection classes are not strongly typed, so all three dictionaries will be created with:
NSMutableDictionary *dictX = [NSMutableDictionary new];
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)];
and etc.
source to share
Since Objective C has no generic types, all you need to type is:
NSMutableDictionary *dict1 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *dict2 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *dict3 = [[NSMutableDictionary alloc] init];
There are several ways to get and set values. The shorthand form is very similar to array access. To set a value with a reduction:
dict1[@"key"] = @"value";
To get the abbreviated value:
NSString *value = dict1[@"key"];
More detailed syntax looks like this:
[dict1 setObject:@"value" forKey:@"key"];
NSString *value = [dict1 valueForKey:@"key"];
source to share