1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
//Foundation中的字典NSDictionary是由键-值对组成的数据集合。key(键)的值必须是唯一的 /*****************不可变字典*****************/ //字典的初始化 NSDictionary *dic1 = [NSDictionary dictionaryWithObject:@ "value" forKey:@ "key" ]; //输出:{key = value}
NSDictionary *dic2 = [NSDictionary dictionaryWithObjects:@ "v1" , @ "k1" , @ "v2" , @ "k2" , @ "v3" , @ "k3" , nil];
NSDictionary *dic3 = [NSDictionary dictionaryWithDictionary:dic2]; //获取字典的数量 int count = [dic2 count]; //输出:count=3(有3组键-值对)
//根据键名获取其值 NSString *string = [dic2 objectForKey:@ "k2" ]; //输出:string=v2
//获取字典的所有key和value NSArray *keyArray = [dic2 allKeys]; //输出:keyArray={k1,k2,k3}
NSArray *valueArray = [dic2 allValues]; //输出:valueArray={v1,v2,v3}
/****************可变字典*********************/ //创建一个字典 NSMutableDictionary *mutableDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@ "v1" , @ "k1" , @ "v2" , @ "k2" , @ "v3" , @ "k3" , nil];
//添加键-值对 //方式一 NSDictionary *dic4 = [NSDictionary dictionaryWithObject:@ "v4" forKey:@ "k4" ];
[mutableDic addEntriesFromDictionary:dic4]; //方式二 【mutableDic setValue:@ "object" forKey:@ "k5" ];
//创建一个空的可变字典 NSMutableDictionary *mutableDic2 = [NSMutableDictionary dictionary]; [mutableDic2 setDictionary:mutableDic]; //NSMutableDictionary *mutableDic2 = [NSMutableDictionary dictionaryWithObject:@"one" forKey:@"k"]; //根据键名删除元素 [mutableDic removeObjectForKey:@ "k3" ];
//删除一组键值对 NSArray *keys = [NSArray arrayWithObjects:@ "k1" , @ "k2" , @ "k3" , nil];
[mutableDic removeObjectsForKeys:keys]; //删除所有元素 [mutableDic removeAllObjects]; /****************遍历字典*************************/ //一般遍历 for ( int index=0; index<[mutableDic count]; index++)
{ NSString *object = [mutableDic objectForKey:[[mutableDic allKeys] objectAtIndex:index]];
NSLog(@ "%@" , object);
} //快速枚举 for (id key in mutableDic)
{ NSString *object = [mutableDic objectForKey:key];
NSLog(@ "%@" , object);
} //通过枚举类型遍历 NSEnumerator *enumerator = [mutableDic keyEnumerator]; id key = [enumerator nextObject]; while (key)
{ id object = [mutableDic objectForKey:key];
NSLog(@ "%@" , object);
key = [enumerator nectObject];
} |
NSDictionary字典
最新推荐文章于 2017-05-12 11:27:47 发布