NSDictionary初始化
//1.创建空的字典
NSDictionary *dict=[[NSDictionary alloc]init];
//或者 NSDictionary *dict=[NSDictionary dictionary];
//2.
NSDictionary *dict1=[[NSDictionary alloc]initWithObjectsAndKeys:@"value1",@"key1",@"value2",@"key2",nil];
//或者 NSDictionary *dict1=[NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"key1",@"value2",@"key2",nil];
//3.读取文件数据
// 获取Documents目录路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSDictionary *dict2=[[NSDictionary alloc]initWithContentsOfFile:docDir];
//或者 NSDictionary *dict1=[NSDictionary dictionaryWithContentsOfFile:docDir];
常用方法
//获取字典数量
NSInteger count=[dict1 count];
//通过key获取对应的value对象
NSObject *valueObj=[dict1 objectForKey:@"key"];
//将字典的key转换成枚举对象,用于遍历
NSEnumerator *enumerator=[dict1 keyEnumerator];
//获取所有值的集合
NSArray *keys=[dict1 allKeys];
//获取所有值的集合
NSArray *values=[dict1 allValues];
可变数组NSMutableDictionary
//初始化一个空的可变字典
NSMutableDictionary *mutableDic1 = [NSMutableDictionary dictionary];
//或者 NSMutableDictionary *mutableDic1=[[NSMutableDictionary alloc]init];
NSMutableDictionary *mutableDic2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"v1",@"key1",@"v2",@"key2",nil];
NSDictionary *mutableDic3 = [NSDictionary dictionaryWithObject:@"v3" forKey:@"key3"];
//向字典2对象中添加整个字典对象3
[mutableDic2 addEntriesFromDictionary:mutableDic3];
//向字典2对象中最佳一个新的key3和value3
[mutableDic2 setValue:@"value3" forKey:@"key3"];
//将空字典1对象内容设置与字典2对象相同
[mutableDic1 setDictionary:mutableDic2];
//将字典中key1对应的值删除
[mutableDic1 removeObjectForKey@"key1"];
//根据指定的数组(key)移除字典1的内容
NSArray *array = [NSArray arrayWithObjects:@"key1", nil];
[mutableDic2 removeObjectsForKeys:array];
//移除字典所有对象
[mutableDic1 removeAllObjects];
遍历字典
//快速枚举
for (id key in dic){
id obj = [dic objectForKey:key];
NSLog(@"%@", obj);
}
//一般枚举
NSArray *keys = [dic allKeys];
int length = [keys count];
for (int i = 0; i < length;i++){
id key = [keys objectAtIndex:i];
id obj = [dic objectForKey:key];
NSLog(@"%@", obj);
}
//通过枚举类型枚举
NSEnumerator *enumerator = [dic keyEnumerator];
id key = [enumerator nextObject];
while (key) {
id obj = [dic objectForKey:key];
NSLog(@"%@", obj);
key = [enumerator nextObject];
}