标签:
////////////////////////////////////////////////////////////////////
//===========字典 集合==========字典 集合=========字典 集合============//
////////////////////////////////////////////////////////////////////
/*
字典用于保存具有映射关系(key-value对)数据的集合
一个 key-value对 认为是一个条目,字典是存储 key-value对 的容器
与数组不同,数组靠下标存取数据,数组的下标是唯一的
字典靠key存取元素,key不能重复,value必须是对象
键值对在字典中是无序存储的
字典分为:不可变字典(NSDictionary)只能读不能更改和可变字典(NSMutableDictionary)
*/
//不可变字典, 初始化字典,一般key值是字符串对象,空值用NSNull对象表示
NSDictionary *dic1 = [NSDictionary dictionaryWithObject:@"value1" forKey:@"key1"];
NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:@"value2",@"key2",@"value3",@"key3",nil];
NSDictionary *dic3 = [NSDictionary dictionaryWithDictionary:dic2];
// NSDictionary *dic4 = @{@"key1": @"value1",@"key2":@"value2"};//语法糖,键值对之间用“,”隔开,key值和value值之间用“:”隔开
//获取字典的数量
NSInteger int1 = [dic1 count];
NSLog(@"%lu",int1);
//通过key值获取value值
NSString *result = [dic2 objectForKey:@"key2"];//根据键值把value值取出来 取出key2对应的value值
NSLog(@"%@",result);
//根据value值取出key值,只能取出所有的key值
NSArray *result2 = [dic2 allKeysForObject:@"value2"];//根据value把key值取出来(只能取所有的key值)
NSLog(@"%@",result2);
//取所有的key值返回的是数组,用数组NSAarry接收
NSArray *keyArray = [dic3 allKeys];
NSLog(@"%@",keyArray);
//取出所有的value值
NSArray *valueArray = [dic3 allValues];
NSLog(@"%@",valueArray);
//将字典的key值变成一个枚举对象用于遍历
NSEnumerator *enumerator = [dic2 keyEnumerator];
//=========================================//
////////可变字典/////////
//初始化,和不可变字典类似
NSMutableDictionary *dic4 = [NSMutableDictionary dictionary];
NSMutableDictionary *dic5 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"value1",@"key1",@"value2",@"key2", nil];
//把一个字典加到另一个里面
[dic4 addEntriesFromDictionary:dic1];
//给字典新增元素
[dic5 setObject:@"value3" forKey:@"key3"];
//把dic5的内容设置成和dic1一样的内容
[dic5 setDictionary:dic1];
//移除所有元素。根据key值一个个一处,也可以把key值设置为array后,把array传递进来
[dic5 removeAllObjects];
[dic5 removeObjectForKey:@"key1"];
[dic5 removeObjectsForKeys:valueArray];
//快速遍历方法
for (id key in dic5) {
id obj = [dic5 objectForKey:key];
NSLog(@"%@",obj);
}
//常用遍历方法
NSArray *aKey = [dic5 allKeys];
NSInteger length = [aKey count];
for (int i = 0; i<length; i++) {
id keyNew = [aKey objectAtIndex:i];
id obj = [dic5 objectForKey:keyNew];
NSLog(@"%@",obj);
}
//利用Enumerator遍历
NSEnumerator *emu1 = [dic5 keyEnumerator];
id key = [emu1 nextObject];
while (key) {
id obj = [dic5 objectForKey:key];
NSLog(@"%@",obj);
key = [emu1 nextObject];
}
标签:
原文地址:http://www.cnblogs.com/54pangzi/p/4472263.html