Reputation: 313
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.
Upvotes: 3
Views: 23353
Reputation: 3077
Since Objective C does not have generic types all you have to type is this:
NSMutableDictionary *dict1 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *dict2 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *dict3 = [[NSMutableDictionary alloc] init];
There's a couple ways to get and set values. The shorthand form is much like accessing arrays. To set a value with shorthand:
dict1[@"key"] = @"value";
To get a value with shorthand:
NSString *value = dict1[@"key"];
More verbose syntax is like so:
[dict1 setObject:@"value" forKey:@"key"];
NSString *value = [dict1 valueForKey:@"key"];
Upvotes: 11
Reputation: 122391
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.
Upvotes: 12