-
创建NSDictionary
//NSDictionary 不可变的,一旦创建,内容就不能添加\删除(不能改动)
//1)创建空字典
NSDictionary *dict1 = [NSDictionary dictionary];
// key value
// zs ---> 张三// ls ---> 李四 // mz ---> 码子 //2)创建只有一组键值对的字典 NSDictionary *dict2 = [NSDictionary dictionaryWithObject:@"zhangsan" forKey:@"zs"]; //3)创建多组键值对的字典 // value值,key值 NSDictionary *dict3 = [NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"k1",@"value2",@"k2", nil];
-
快速创建NSDictionary
//@{,,key值:value值,,,}; //key值不能重复: //如果重复了,也不会报错 //如果重复了,最后添加的将不能够保存到字典中 NSDictionary *dict4 = @{@"zs":@"zhaosi",@"zs":@"zhangsan",@"ls":@"lisi",@"bz":@"banzhang"};
-
NSDictionary基本使用方法:
-(NSUInteger)count; //返回字典的键值对数目
-(id)bojectForKey:(id)aKey; //根据key取出valueNSDictionary *dict4 = @{@"zs":@"zhaosi",@"zs":@"zhangsan",@"ls":@"lisi",@"bz":@"banzhang"}; NSLog(@"%@",dict4); //以%@格式打印字典,控制台输出一个{ } //5)获取字典的长度 NSLog(@"%lu",dict4.count); //6)根据key值取出value值 // zs zhaosi // key NSString *str = [dict4 objectForKey:@"zs"]; NSLog(@"str = %@",str);
-
NSDictionary遍历方法:
//第一步:获取所有的key
//第二步:根据key获取value//第一种方法 for(NSString *key in dict4){ NSLog(@"key = %@,value = %@",key,[dict4 objectForKey:key]); } //第二种方法(常用方法) key value stop [dict4 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { NSLog(@"%@ --> %@",key,obj); }];
-
NSDictionary简写形式
//1)用简写形式定义一个字典
NSDictionary *dict = @{@"zbz":@"zhangbozhi",@"cgx":@"chenguanxi",@"xzmly":@"hello"};//2)用简写形式,获取key对应的value NSLog(@"%@",dict[@"zbz"]);
NSDictionary文件操作
//3)把字典保存到文件中
// BOOL isWrite = [dict writeToFile:@"/Users/zhaoxiaohu/Desktop/dict.plist" atomically:YES];
// if (isWrite) {
// NSLog(@"写入成功");
// }
//4)从文件中读取字典
NSDictionary *readDict = [NSDictionary dictionaryWithContentsOfFile:@"/Users/zhaoxiaohu/Desktop/dict.plist"];
NSLog(@"readDict = %@",readDict);