NSDictionary和NSMutableDictionary的用法
NSDictionary 翻译过来就是“字典”,键值对;日常生活中,“字典”的作用:通过一个拼音或者汉字,就能找到对应详细的解释。
NSDictionary 的作用类似:通过一个key(键),就能找到对应的value(值);
NSDictionary是不可变的,一旦初始化完毕后,里面的内容就无法修改.
NSDictionary的创建:
NSDictionary *dict1 = [NSDictionary dictionary]; //空字典
//含有多对键值对的数据
NSDictionary *dict2 = [NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"k1",@"value2",@"k2",nil];
//将一个字典赋值给另一个字典
NSDictionary *dict3 = [NSDictionary dictionaryWithDictionary:dict2];
//只含有一对键值对的字典
NSDictionary *dict4 = [NSdictionary ditctionaryWithObject:@"value1" forKey:@"k1"];
//快速创建字典:
NSDictionary *dict5 = @{@”k1”:@”value1”,@”k2”:@”value2”};
访问其中value
NSString *str = [dict objectForKey :@”k1];
NSString *str2 = dict[@”k2”];
读文件:
NSString *path = [[NSBundle mainBundle] pathForResource:@"dict.plist" ofType:nil]; //文件路径
NSDictionary *dict2 = [NSDictionary dictionaryWithContentsOfFile:path];
写文件:
BOOL flag = [dict writeToFile:@”/users/zzf/Desktop/dict.plist” atomically:YES];
if(flag)
{
NSLog(@”写入成功”);
}
字典遍历:
第一种方法:
NSDictionary *dict5 = @{@”k1”:@”value1”,@”k2”:@”value2”};
for(NSString *str in dict5)
{
<span style="white-space:pre"> </span>NSLog(@"%@ --> %@",str,dict5[str]);
}
第二种方法:
NSDictionary *dict5 = @{@”k1”:@”value1”,@”k2”:@”value2”};
[dict5 enumerateKeysAndObjectsUsingBlock:^(id key ,id obj ,BOOL *stop){
NSLog(@"%@ --> %@",key,obj);
}];
NSMutableDictionary是NSDictionary的子类;NSMutableDictionary是可变字典,随时可以往里面添加、更改和删除元素。
动态字典的创建:
NSMutableDictionary *dict1 = [NSMutableDictionary dictionary]; //空字典
//含有多对键值对的数据
NSMutableDictionary *dict2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"value1",@"k1",@"value2",@"k2",nil];
//将一个字典赋值给另一个字典
NSMutableDictionary *dict3 = [NSMutableDictionary dictionaryWithDictionary:dict2];
//创建一对键值对
NSMutableDictionary *dict4 = [NSMutableDictionary ditctionaryWithObject:@"value1" forKey:@"k1"];
添加键值对:
[dict setValue:@”lisi” forKey:@”ls”];
删除键值对:
[dict removeObjectForKey:@”ls”];
[dict removeAllObjects];
修改键值对:
[dict setObject:@”zhaosi” forKey:@”ls”];
Dict[@”ls”] = @”zhaosi”;
查找键值对:
NSArray * arr = [dict allKeys];
if(arr containsObject:@”ls”])
{
<span style="white-space:pre"> </span>NSLog(@“含有这个键值对”);
}
NSDictionary 的创建的类方法:
+(id)dictionary;
+(id)dictionaryWithContentsOfFile:(NSString *)path;
+(id)dictionaryWithContentsOfURL:(NSString *)path;
+(id)dictionaryWithDictionary:(NSDictionary*)dict;
+(id)dictionaryWithObjectsAndKeys;
+(id)ditctionaryWithObject:(id)data forKey:(id)key;