标签:
简单分享下,希望大牛们多多指点迷津,逐步修改,完善不足支持。借鉴之处,还请谅解
#pragma mark NSDictionary的初始化
NSDictionary *dict=[NSDictionary dictionaryWithObject:@"v" forKey:@"k1"];
//NSDictionary是不可变的
NSLog(@"%@",dict[@"k1"]); //[dict objectForKey:@"k1"]
//字典的键,如同数组的索引,只不过键是OC对象:array[index]
dict=[NSDictionary dictionaryWithObjectsAndKeys:@"v1",@"k1",@"v2",@"k2", nil]; //最常用
NSArray *objects=[NSArray arrayWithObjects:@"v1",@"v2",@"v3", nil];
NSArray *keys=[NSArray arrayWithObjects:@"k1",@"k2",@"k3", nil];
dict=[NSDictionary dictionaryWithObjects:objects forKeys:keys];
#pragma mark NSDictionary的常用方法
NSLog(@"%zi",dict.count); //计算有多少个键值对
id obj=[dict objectForKey:@"k2"]; //根据键取出值:id类型
//NSDictionary不可变,只能取值,不能修改
NSString *path=@"/Users/administrator/Desktop/text.txt";
[dict writeToFile:path atomically:YES]; //将字典写入文件中(xml格式)
dict=[NSDictionary dictionaryWithContentsOfFile:path];
//从文件(xml格式)中读取内容
NSArray *alkeys=[dict allKeys]; //返回所有键(乱序)
NSArray *alobjs=[dict allValues]; //返回所有值
NSArray *okeys=[dict allKeysForObject:@"v2"]; //返回一个值对应的所有键
NSArray *objs=[dict objectsForKeys:keys notFoundMarker:@"not"];
//如果键找不到对应值时,用mark代替
#pragma mark NSDictionary遍历
for (id key in dict){ //for-in:遍历字典的所有key
id value=[dict objectForKey:key]; //对应键取出值
}
NSEnumerator *enumer=[dict keyEnumerator]; //对象迭代器
//key迭代器遍历 & [dict objectEnumerator];-value迭代器遍历
id key=nil;
while (key=[enumer nextObject]) {
id value=[dict objectForKey:key];
}
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
//block遍历
NSLog(@"%@---%@",key,obj);
}];
//内存管理问题:创建类的对象放入字典,会做一次retain操作,当字典被销毁时,所有键值都会release一次
#pragma mark NSMutableDictionary 可变字典
NSMutableDictionary *dic=[NSMutableDictionary dictionary];
[dic addEntriesFromDictionary:dict]; //添加其他字典到当前字典中
[dic setObject:@"v" forKey:@"k"];
[dic removeObjectForKey:@"k"]; //删除对应键的值
[dic removeAllObjects]; //删除所有键值对
[dic removeObjectsForKeys:keys]; //删除多个键的值
//字典没有排序属于乱序
标签:
原文地址:http://www.cnblogs.com/Miracle-Huang/p/5516153.html