NSDictionary不可变,一旦创建,内容就不能删除和添加(不能改动)
1)创建空字典
NSDictionary *diat = [NSDictionary dictionary];
2)创建只有一组键值对的字典
NSDictionary *dict2 = [NSDictionary dictionaryWithObject:@"zhangsan" ForKey:@"zs"];
3)创建多组键值对的字典,使用value值,key值
NSDictionary *dict3 = [NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"k1",@"value2",@"k2",nil];
注意:
字典的key值和value值都必须是对象
NSLog(@"%@",dict3);//以%@格式打印字典,控制台输出一个{ }
4)快速创建一个字典
@{key值:value值,,,};
key值不能重复:如果重复了也不会报错,如果重复了,最后添加的将不能够保存到字典中
NSDictionary *dict4 = @{@"zs":@"zhaosi",@"zs",@"zhangsan",@"ls":@"lisi",@"bz":@"banzhang"};
NSLog(@"%@",dict4);
5)获取字典的长度
NSLog(@"%lu",dict4.count);
6)根据key值取出value值
NSString *str = [dict4 objectForKey:@"zs"];
NSLog(@"str = %@",str);
7)字典的遍历问题
第一步:获取所有的key
第二步:根据key获取value
for(NSString *key in dict4){
NSLog(@"key = %@,value = %@",key,[dict4 objectForKey:key]);
}
[dict enumerateKeysAndObjectsUsingBlock:^(id key,id obj,BOOL *stop)];
NSLog(@"%@--->%@",key,obj);
1)用简易形式定义一个字典
NSDictionary *dict = @{@"zbz":@"zhangbozhi",@"cgx":@"chengguanxi",@"xzmly":@"hello"}
2)用简易形式,获取key对应的value
NSLog(@“%@”,dict[@"zbz"];)
3)把字典保存到文件中
BOOL isWrite = [dict writeToFile:@"/users/zhaoxiaohu/Desktop/dict.plist" atomically:YES];
if (isWrite){
NSLog(@"写入成功");
}
4)从文件中读取字典
NSDictionary *readDict = [NSDictionary dictionaryWithContentsOfFile:@"/user/zhaoxiaohu/Desktop/dict.plist"];
NSLog(@"readDict = %@",readDict);
--------从文件中读取数组:NSArray *arr = [NSArray arrayWithContentsOfFile:@"/User/sdfkljsdkfajskdfjaskd"];
NSArray *lnArr = [NSArray arrayWithObjects:@"dalian",@"shenyang",nil];
NSArray *sdArr = [NSArray arrayWithObjects:@"jinan",@"weifang",nil];
NSDictionary *citys = [NSDictionary dictionaryWithObjectsAndKeys:lnArr,@"ln",sdArr,@"sd",ni;];
NSLog(@"citys = %@",citys);
[citys writeToFile:@"/user/sdlkfjklsajdfkl/citys.plist" atomically:YES];
//读取city.plist
NSDictionary *citysDict = [NSDictionary dictionaryWithContentsOfFile:@"/user/sdfsdfsdfdsf/citys.plist"];
遍历
[cityDict enumerateKeysAndObjectsUsingBlock:^(id key,id obj,BOOL *stop){
//NSLog(@"key:%@,value:%@",key,obj);
for(NSString *str in obj) {
NSLog(@"city = %@",str);
}
}];
获取每个数组
NSArray *arr = cityDict[@"ln"];
NSLog(@"%@",[arr lastObject]);