1、概念
字典
作用:类似有一个key键,可以通过key找到对应的值
是不可变的,一旦创建,初始化完毕就不能改变
// 1)创建空字典,无意义
NSDictionary *dict = [NSDictionary dictionary];
// 2)创建只有一组键值对的字典
// key valu
// zs 张三
NSDictionary *dict1 = [NSDictionary dictionaryWithObject:@"张三" forKey:@"zs"];
// 3)创建多组键值对的字典 值 key
NSDictionary *dict2 = [NSDictionary dictionaryWithObjectsAndKeys:@"valu1",@"k1",@"valu2",@"k2", nil];
// 以%@打印字典,汉字打印的是UTF-8编码,字典打印无序
// 注意:字典的key值和valu值都是对象
// 快速创建字典,格式:@{,,key值:valu值,};
NSDictionary *dict3 = @{@"key1":@"valu1",@"key2":@"valu2"};
注意: 成对出现,
key值不能重复,如果重复不会报错,但是不会显示出来最后添加的
2、基本使用
// 返回key值数,获取字典长度
NSLog(@"%lu",[dict3 count]);
// 根据key值取出valu值
NSString *str = [dict3 objectForKey:@"key1"];
NSLog(@"%@",str);
// 遍历字典
// 1)获取key值
// 2)根据key获取value值
// forin快速枚举遍历
for (NSString *key in dict3) {
NSLog(@"key = %@,value = %@",key,[dict3 objectForKey:key]);
}
// 2block方法遍历,可以控制什么时候停止
[dict3 enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
NSLog(@"%@--%@",key,obj);
}];
4、简写形式
NSDictionary *dict3 = @{@"key1":@"valu1",@"key2":@"valu2"};
简写的读取
NSLog(@"%@",dict3[@"key1"]);
// 1)把字典保存到文件中
if ([dict3 writeToFile:@"/Users/snowimba/Desktop/dict.plist" atomically:YES]){
NSLog(@"写入成功!");
}
// 把字典从文件中读取
NSDictionary *dict4 = [NSDictionary dictionaryWithContentsOfFile:@"/Users/snowimba/Desktop/dict.plist"];
NSLog(@"%@",dict4);
// 应用,省会用数组和字典存储文件
// 用数组建立每个省下面的城市,字典里面key存省会名称
NSArray *arr1 = @[@"dalian",@"shengyang"];
NSArray *arr2 = @[@"baoding",@"shijiazhuang"];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:arr1,@"ln",arr2,@"hb", nil];
[dict writeToFile:@"/Users/snowimba/Desktop/shenghui.plist" atomically:YES];
NSDictionary *readdict = [NSDictionary dictionaryWithContentsOfFile:@"/Users/snowimba/Desktop/shenghui.plist"];
for (NSString *key in readdict) {
NSLog(@"key = %@,value = %@",key,[readdict objectForKey:key]);
}
[readdict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
NSLog(@"key:%@, value:%@",key,obj);
}];
5、动态字典
可变的字典,NSMutableDictionary是子类,继承所有方法,可变的
增
删
改
查
// 可变字典
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
// 添加键值
[dict setObject:@"value1" forKey:@"key1"];
[dict setObject:@"value2" forKey:@"key2"];
[dict setObject:@"value3" forKey:@"key3"];
// 删除键值
[dict removeObjectForKey:@"key1"];
// 全部删除
// [dict removeAllObjects];
// 修改
[dict setObject:@"value4" forKey:@"key2"];
dict [@"key2"] = @"xxx";
NSLog(@"%@",dict);
// 查找
NSArray *arr = [dict allKeys];
[arr containsObject:@"key2"];
}
5、集合和字典对比
集合
有序
下标访问
字典
无序
key值访问
|
|