初始化NSMutableDictionary

Sib*_*bir 3 objective-c nsmutabledictionary ios

我正在开发一个iOS应用程序,我想在其中使用NSMutableDictionary.基本上我正在做的是将java代码转换为objectiveC.

所以在java中我有这样的东西:

Map<String, ClassA> dict1 = new HashMap<>();
Map<Integer,Character> dict2 = new HashMap<>();
Map<Integer, Map<String,String>> dict3 = new HashMap<>();
Run Code Online (Sandbox Code Playgroud)

有人可以指导我作为上述三行使用的Obj-C等效代码,NSMutableDictionary以及如何在字典中设置和获取对.

tro*_*foe 12

Objective-C集合类不是强类型的,因此将使用以下命令创建所有三个字典:

NSMutableDictionary *dictX = [NSMutableDictionary new];
Run Code Online (Sandbox Code Playgroud)

为了填充字典使用[NSMutableDictionary setObject:forKey:]:

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

等等


jer*_*e10 9

由于Objective C没有泛型类型,所以你需要输入的是:

NSMutableDictionary *dict1 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *dict2 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *dict3 = [[NSMutableDictionary alloc] init];
Run Code Online (Sandbox Code Playgroud)

有几种方法可以获取和设置值.简写形式很像访问数组.要用速记设置值:

dict1[@"key"] = @"value";
Run Code Online (Sandbox Code Playgroud)

要获得速记值:

NSString *value = dict1[@"key"];
Run Code Online (Sandbox Code Playgroud)

更详细的语法是这样的:

[dict1 setObject:@"value" forKey:@"key"];
NSString *value = [dict1 valueForKey:@"key"];
Run Code Online (Sandbox Code Playgroud)