标签:
/**************** NSDictionary *****************/
//创建一个新的字典
NSDictionary *dictionary1=[NSDictionary dictionary];
NSDictionary *dictionary2=[[NSDictionary alloc]init];
NSLog(@"dictionary1:%@,dictionary2:%@",dictionary1,dictionary2);
//创建一个包含一对键值对的字典
NSDictionary *dictionary3=[NSDictionary dictionaryWithObject:@"value" forKey:@"key"];
NSLog(@"dictionary3:%@",dictionary3);
//创建一个包含多对键值对的字典
NSDictionary *dictionary4=[NSDictionary dictionaryWithObjects:@[@"a",@"b",@"c"] forKeys:@[@"k1",@"k2",@"k3"]];
NSLog(@"dictionary4:%@",dictionary4);
NSDictionary *dictionary5=[NSDictionary dictionaryWithObjectsAndKeys:@"a",@"k1",@"b",@"k2", nil];
NSLog(@"dictionary5:%@",dictionary5);
//根据已有的字典创建字典
NSDictionary *dictionary6=[NSDictionary dictionaryWithDictionary:dictionary5];
NSLog(@"dictionary6:%@",dictionary6);
//获取字典中元素的个数
NSLog(@"dictionary6 count = %d",(int)dictionary6.count);
//获取某个key值对应的value
NSLog(@"dictionary6 key is k1 value is %@",[dictionary6 valueForKey:@"k1"]);
NSArray *array=[NSArray arrayWithObjects:@"iphone",@"android",@"winphone", nil];
NSDictionary *dictionary7=[NSDictionary dictionaryWithObject:array forKey:@"phone"];
NSArray *newArray=[dictionary7 valueForKey:@"phone"];
NSLog(@"newArray:%@",newArray);
//获取字典中所有的key
NSDictionary *dictionary8=[NSDictionary dictionaryWithObjects:@[@"a",@"b",@"c"] forKeys:@[@"k1",@"k2",@"k3"]];
NSArray *keyArray=[dictionary8 allKeys];
NSLog(@"keyArray:%@",keyArray);
//所有的key转换成枚举
NSEnumerator *enum1=[dictionary8 keyEnumerator];
for (NSString *string in enum1) {
NSLog(@"%@",string);
}
/**************** NSMutableDictionary *****************/
NSMutableDictionary *mutableDic1=[NSMutableDictionary dictionaryWithObjects:@[@"a",@"b",@"c"] forKeys:@[@"k1",@"k2",@"k3"]];
//添加
[mutableDic1 setObject:@"value1" forKey:@"key1"];
NSLog(@"mutableDic1 : %@",mutableDic1);
NSMutableDictionary *mutableDic2=[NSMutableDictionary dictionaryWithObjects:@[@"1",@"2"] forKeys:@[@"k4",@"k5"]];
//添加字典元素到另一个字典中
[mutableDic1 addEntriesFromDictionary:mutableDic2];
NSLog(@"mutableDic1%@ mutableDic2%@",mutableDic1,mutableDic2);
//把当前字典所有元素替换为新的字典中的元素
//[mutableDic1 setDictionary:mutableDic2];
NSLog(@"mutableDic1 : %@",mutableDic1);
//删除
[mutableDic1 removeObjectForKey:@"key1"];
NSLog(@"mutableDic1 : %@",mutableDic1);
[mutableDic1 removeObjectsForKeys:@[@"k4",@"k5"]];
NSLog(@"mutableDic1 : %@",mutableDic1);
//根据指定key值替换value值
[mutableDic1 setObject:@"new" forKey:@"k1"];
NSLog(@"mutableDic1 : %@",mutableDic1);
标签:
原文地址:http://www.cnblogs.com/ningguozhu/p/4941546.html