首先来定义一个字典
NSMutableDictionary *dic =[NSMutableDictionary dictionaryWithObjectsAndKeys:@"1",@"2",@"3",@"4",@"5",@"6", nil];
[setValue: forKey:]和[setObject: forKey:]相同点
1.当key和value对应的都有值
当key和value都有值时,key所对应的值在字典中不存在时,就可以添加
当key已经存在时,都不会创建键值对
在字典中,value可以重复,但key必须只有一个
代码段:NSMutableDictionary *dic =[NSMutableDictionary dictionaryWithObjectsAndKeys:@"1",@"2",@"3",@"4",@"5",@"6", nil];
(1)[dic setValue:@"6"forKey:@"7"];
NSLog(@"%@",dic);
(2)[dic setObject:@"6" forKey:@"7"];
NSLog(@"%@",dic);
两种情况结果都是:2015-07-24 20:46:25.860 OC07_类的扩展[1543:105974] {
2 = 1;
4 = 3;
6 = 5;
7 = 6; }
2.当key的值为空时
[setValue: forKey:]和[setObject: forKey:]在创建键值对时都会直接崩溃,也就是说在添加键值对时,key必须有对应的值,不能为空
[setValue: forKey:]和[setObject: forKey:]区别
1.kvc中创建键值对用:[setValue: forKey:]
代码段:NSMutableDictionary *dic =[NSMutableDictionary dictionaryWithObjectsAndKeys:@"1",@"2",@"3",@"4",@"5",@"6", nil];
[dic setValue:nil forKey:@"2"];
NSLog(@"%@",dic);
结果: 2015-07-24 20:37:49.603 OC07_类的扩展[1511:103886] {
4 = 3;
6 = 5;
}
在kvc中当 key的值在字典中有相对应的值时,value值为空时,[setValue: forKey:]对应的功能是移除键值对
2.字典中创建键值对用:[setObject: forKey:]
代码段:NSMutableDictionary *dic =[NSMutableDictionary dictionaryWithObjectsAndKeys:@"1",@"2",@"3",@"4",@"5",@"6", nil];
[dic setObject:nil forKey:@"4"];
NSLog(@"%@",dic);
结果为:崩溃
在用[setObject: forKey:]创建键值对时,key的值在字典中有相对应的值时,value值为空时,整个程序直接崩溃