1 // 初始化一个空字典
2 // NSDictionary *dictionary = [[NSDictionary alloc] init];
3 // 初始化一个空典
4 // NSDictionary *dictionary1 = [NSDictionary dictionary];
5 // 初始化的同时 添加一对键值
6 // NSDictionary *dictionary2 = [NSDictionary dictionaryWithObject:@"value" forKey:@"key"];
7 // 初始化的同时添加多对键值
8 // 前面是值 可以是任意类型
9 // 后面是key 必须是字符串
10 NSDictionary *dictionary3 = [NSDictionary dictionaryWithObjectsAndKeys:@"object",@"key",@"object1",@"key1", @"object2",@"key2",nil];
11 // 字典的新方法
12 // 前面是key 后面是值 与之前的方法的键值相反
13 NSDictionary *dictionary4 = @{@"key":@"值",@"key1":@"值1"};
14 NSLog(@"%@",dictionary3);
15 NSLog(@"%@",dictionary4);
16
17 // objectForKey :通过key曲字典里面的值
18 NSLog(@"%@",[dictionary4 objectForKey:@"key"]);
19 // 第二种取值方式
20 NSLog(@"%@",dictionary4[@"key1"]);
21
22
23 // 1用字典 表达出自己的考试分数 语文 25 数学 1000 英语 3
24
25 NSDictionary *scrose = [NSDictionary dictionaryWithObjectsAndKeys:@"25",@"chinese",@"1000",@"math",@"3",@"English", nil];
26 [scrose objectForKey:@"chinese" ];
27 [scrose objectForKey:@"math"];
28 [scrose objectForKey:@"English"];
29 NSLog(@"%@ %@ %@",[scrose objectForKey:@"chinese" ],[scrose objectForKey:@"math"],[scrose objectForKey:@"English"]);
30 NSDictionary *year = [NSDictionary dictionaryWithObjectsAndKeys:@"发芽",@"春",@"开花",@"夏",@"结果",@"秋",@"凋谢",@"冬",@"发芽1",@"春1",@"开花1",@"夏1",@"结果1",@"秋1",@"凋谢1",@"冬1", nil];
31 // 输出一个key对应的值
32 NSLog(@"%@",[year objectForKey:year.allKeys[0]]);
33 // 遍历所有的键值
34 // allKeys是所有 key的一个数组
35 // count得到数字内有多少个元素
36 for(NSString *key in year.allKeys){
37 NSLog(@"%@ %@",key,[year objectForKey:key]);
38 }
39
40
41 NSLog(@"%@ %@ %@ %@",[year objectForKey:@"春"],[year objectForKey:@"夏"],[year objectForKey:@"秋"],[year objectForKey:@"冬"]);
42
执行结果: