標籤:
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
執行結果:
objective-c字典