OC中的Dictionary就是有键(key)-值(value)对组成的。其中key通常为字符串类型,但是也可以为其他类型。在字典中是没有顺序可言的,也就是说,字典的输入和输入的顺序不一定就是一致的,通常都是不一致的。使用字典的好处就是:1.方便查找;2.方便删改。
注意:字典里多个键对的值可以是相同的,但是健不能相同,必须唯一。
▲不可变字典(NSDictionary)
1.创建不可变字典:
①NSDictionary *dic_1 = @{@"小明":xm};
②NSDictionary *dic_2 = [NSDictionary dictionary];
③NSDictionary *dic_3 = [[NSDictionary alloc] init];
④NSDictionary *dic_4 = [NSDictionary dictionaryWithDictionary:dic];
⑤NSDictionary *dic_5 = [[NSDictionary alloc] initWithDictionary:dic];
//初始化一个键值对
NSDictionary *dic_3 = [NSDictionary dictionaryWithObject:xm forKey:@"小明"];
//创建拥有多个键值对的字典
NSDictionary *dic_4 = [NSDictionary dictionaryWithObjects:@[xm, xh, xg] forKeys:@[@"xiaoming", @"xiaohong", @"xiaogang"]];
2.获取字典中键值对的个数
NSLog(@"The count is %li.", dic_4.count);
3.获取所有的键keys(字符串对象)
NSArray *allKeys = [dic_4 allKeys];
4.获取所有的值values
NSArray *allValue = [dic_4 allValues];
5.遍历一个字典(快速循环)
for (NSString *key in allKeys){
NSLog(@"key=%@:value=%@", key, [dic_4 objectForKey:key]);
}
6.通过key获取对应的value
NSArray *tempArray = [dic_4 objectForKey:@"xiaoming"];
▲可变字典(NSMutableDictionary)
1.创建可变字典
NSMutableDictionary *mDic = [NSMutaleDictionary dictionaryWithCapacity:0];
2.添加键值对
[mDic setObject:@"xiaoming", forKey:@"name"];
[mDic setObject:pArray forkey:@"name"];
3.删除键值对
[mDic removeObjectForKey:@"name"];
[mDic removeObjectsForKeys:@[@"name", @"nb", @"adfsdf"];
[mDic removeAllObjects];
4.更改某个键值对的值
[mDic setObject:@"xiaogang", forKey:@"name"];
①当key存在时,替换Object的值;
②当key不存在时,为添加键值对。
网友评论