本文共 3544 字,大约阅读时间需要 11 分钟。
字典使用Key-Value的形式储存数据。 字典中的对象储存没有顺序,使用key来表示每个对象。 cocoa框架中的字典:NSDictionary和NSMutableDictionary NSMutableDictionary是NSictionary的子类,能使用其所有方法。 NSMutableDictionary是NSDictionary的可修改版本
1 #import 2 int main(int argc, const char * argv[]) 3 { 4 @autoreleasepool { 5 //不可变字典NSDictionary 6 //字典的创建 7 NSDictionary *dic1=[NSDictionary dictionaryWithObject:@"velue" forKey:@"k1"];//一个键 一个值 8 NSDictionary *dic2=[NSDictionary dictionaryWithObjectsAndKeys:@"v1",@"k1",@"v2",@"k2",@"v3",@"k3",@"v4",@"k4",@"v5",@"k5",nil];//创建多个键 多个值 9 NSDictionary *dic3=[NSDictionary dictionaryWithDictionary:dic1];//直接把dic内容给dic310 NSLog(@"dic1:%@",dic1);11 NSLog(@"dic2:%@",dic2);12 NSLog(@"dic3:%@",dic3);13 14 //获取字典的数量15 int count=[dic2 count];16 NSLog(@"%d",count);17 //获取k3的value18 NSString *string=[dic2 objectForKey:@"k3"];19 NSLog(@"value:%@",string);20 21 //获取字典中所有的key和value22 NSArray *keyArray=[dic2 allKeys];23 NSArray *valueArry=[dic2 allValues];24 NSLog(@"keyArray:%@valueArry:%@",keyArray,valueArry);25 26 27 ////28 //可变字典NSMutableDictionary29 NSMutableDictionary *mutableDic1=[NSMutableDictionary dictionaryWithObjectsAndKeys:@"v1",@"k1",@"v2",@"k2",@"v3",@"k3",@"v4",@"k4",@"v5",@"k5", nil];30 //上面是类方法直接赋值 下面是实例方法开辟空间并赋值31 NSMutableDictionary *mutableDic=[[NSMutableDictionary alloc]initWithObjectsAndKeys:@"v1",@"k1",@"v2",@"k2",@"v3",@"k3",@"v4",@"k4",@"v5",@"k5", nil];32 33 //将一个字典中的velue和key添加到另外一个字典中34 NSDictionary *dic4=[NSDictionary dictionaryWithObject:@"v6" forKey:@"k6"];35 [mutableDic addEntriesFromDictionary:dic4];36 NSLog(@"MutableDic%@",mutableDic);37 38 //向字典中添加新的velue和key39 [mutableDic setValue:@"object" forKey:@"key"];40 NSLog(@"%@",mutableDic);41 42 43 //创建一个空的字典数组44 NSMutableDictionary *mutableDic2=[NSMutableDictionary dictionary];45 [mutableDic2 setDictionary:mutableDic];//46 NSLog(@"dic2:%@",mutableDic2);47 48 //通过制定key删除49 [mutableDic2 removeObjectForKey:@"k4"];50 NSLog(@"dic2:%@",mutableDic2);51 52 //删除多个键值53 NSArray *keys=[NSArray arrayWithObjects:@"k1",@"k2",@"k3", nil];54 [mutableDic2 removeObjectsForKeys:keys];55 NSLog(@"dic2:%@",mutableDic2);56 57 58 //删除全部键值59 // [mutableDic2 removeAllObjects];60 // NSLog(@"dic2:%@",mutableDic2);61 62 63 //遍历字典 一般的方法64 for (int index=0;index<[mutableDic1 count]; index++) {65 NSString *object=[mutableDic1 objectForKey:[[mutableDic1 allKeys]objectAtIndex:index]];66 NSLog(@"object:%@",object);67 }68 //快速枚举69 NSLog(@"____________________");70 for (NSString *key in mutableDic1) {71 NSString *object=[mutableDic1 objectForKey:key];72 NSLog(@"object:%@",object);73 }74 NSLog(@"____________________");75 //使用枚举类型76 NSEnumerator *enumerator=[mutableDic1 keyEnumerator];77 id key;78 while(key=[enumerator nextObject]){79 id object=[mutableDic1 objectForKey:key];80 NSLog(@"object:%@",object);81 82 }83 }84 return 0;85 }
来源:
本文转自夏雪冬日博客园博客,原文链接:http://www.cnblogs.com/heyonggang/p/3449089.html,如需转载请自行联系原作者