------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------
1.介绍
NSDictionary和NSMutableDictionary都是以键值对的方式存储数据,通过key来得到对应的value。除了类可以描述一个对象的属性外,我们也可以通过NSDictionary来描述对象的人物属性。NSMutableDictionary和NSDictionary不同点就是NSMutableDictionary是可变的。这两个对象对数据的存储都是无序的。
代码事例用处见注释。
//NSDictionary初始化
NSDictionary *dic1=@{@"name":@"chendc",@"weight":@"60kg"};
//NSDictionary初始化
NSDictionary *dic2=[NSDictionary dictionaryWithObject:@"name" forKey:@"chendc"];
//NSDictionary初始化
NSDictionary *dic3=[NSDictionary dictionaryWithObjects:@[@"chendc",@"60kg"] forKeys:@[@"name",@"weight"]];
//NSMutableDictionary初始化
NSMutableDictionary *mdic1=[NSMutableDictionary dictionaryWithDictionary:dic1];
//NSMutableDictionary初始化
NSMutableDictionary *mdic2=[NSMutableDictionary dictionaryWithObject: @"chendc" forKey:@"name"];
//当mdic中没weight这个键值对的时候是增加键值对
[mdic2 setObject:@"60kg" forKey:@"weight"];
//当mdic中有weight这个键值对的时候是修改
[mdic2 setObject:@"50kg" forKey:@"weight"];
NSLog(@"%@",mdic2);
/*
NSDictionary的遍历
通过[dic3 allKeys]返回所有的keys
在通过key获得value
*/
NSArray *array=[dic3 allKeys];
for (int i=0; i<array.count; i++) {
NSLog(@"key-%@ value-%@",array[i],dic3[array[i]]);
}