1 //字典:(关键字 值)
2 // NSArray *array = [NSArray array];//空数组
3 // NSDictionary *dictionary = [NSDictionary dictionary];//空字典
4 NSDictionary *my = [NSDictionary dictionaryWithObject:@"objective" forKey:@"key"];
5 NSLog(@"%@",my);
6 NSDictionary *to = [NSDictionary dictionaryWithObjectsAndKeys:@"123",@"abc",@"456",@"efg" ,nil];//创建包含多个值的字典
7 NSLog(@"%@",to);
8 NSDictionary *me = @{
9 @"a":@"1",
10 @"b":@"2"
11 };
12 NSLog(@"%@,%li",me,me.count);
13 NSString *s = [me objectForKey:@"a"];//键值对应的对象
14 NSString *ss = me[@"b"];//跟数组差不多
15 NSLog(@"%@,%@",ss,s);
16
17 // NSArray *keyArr = [me allKeys];
18 // for(NSString *key in keyArr)
19 // {
20 // NSLog(@"%@ = %@",key,me[key]);
21 // }
22
23 NSDictionary *niubi = [NSDictionary dictionaryWithObjectsAndKeys:@"liyuanfang",@"direnjie",@"Moran ",@"fuermosi",@"kenanfushou",@"kenan" ,nil];//创建包含多个值的字典
24 NSArray *keyArr = [niubi allKeys];//取字典中的所有键值
25 for(NSString *key in keyArr)
26 {
27 NSLog(@"%@问%@这事你怎么看?",key,niubi[key]);
28 }
29 /**********************************************************************************/
30 //取出字典中所有的值
31 NSArray *valueArr = [me allValues];
32 NSLog(@"取字典中的所有键对应的值%@",valueArr);
33
34 //字典既然存在,那么开发者肯定想到要方便的使用它
35 //然而就有了,可以独立取出键或值的方法:allKeys和allValues
36 //因为他们是数组属性,所以需要放到新建的数组对象中
37
38 //枚举器中OC语言中一个遍历的有效方法,
39 //应用时,一般先通过.....Enumerator获取枚举器,存放到其对应的类型NSEnumerator对象中
40 //这个对象会有一个自动向下遍历的方法nextObject
41 //先获取字典中key的枚举器,然后遍历该枚举器,获取key对应的值
42 NSEnumerator *e = [me keyEnumerator];
43 id obj;
44 while (obj = [e nextObject]) {
45 NSLog(@"%@ = %@",obj,me[obj]);
46 }
47
48 //获取value对应的枚举器
49 NSEnumerator *a = [me objectEnumerator];
50 while(obj = [a nextObject])
51 {
52 NSLog(@"%@",obj);
53 }
54
55 //键和对象列举块,stop代表遍历停止
56
57 [me enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
58
59 NSLog(@"key=%@,value = %@",key,obj);
60 }];
可变字典
1 NSMutableDictionary *aa = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"a",@"1",@"b",@"2", nil];
2 //增
3 [aa setObject:@"c" forKey:@"3"];
4 NSLog(@"%@",aa);
5 [aa setValue:@"d" forKey:@"4"];
6 NSLog(@"%@",aa);
7 //减
8 [aa removeObjectForKey:@"4"];
9 NSLog(@"%@",aa);
10 [aa removeAllObjects];
11 NSLog(@"%@",aa);