标签:
OC中Foundation框架中有字典类,字典分不可变字典(NSDictionary)和可变字典(NSMutableDictionary),它们的使用如下:
不可变字典:
1 //------------------不可变字典------------------ 2 3 // 创建字典对象、并打印输出 4 NSDictionary *dic = [NSDictionary dictionaryWithObject:@"onevalue" forKey:@"firstkey"]; 5 NSLog(@"%@",dic); 6 7 // 创建字典对象,并打印输出 8 NSDictionary *dicc = [NSDictionary dictionaryWithObjectsAndKeys:@"onevalue", @"firstkey", @"twovalue", @"secondkey",@"threevalue", @"thirdkey", @"threevalue", @"forthkey",nil]; 9 NSLog(@"%@",dicc); 10 11 // 输出某个键对应的值对象 12 NSLog(@"%@",[dicc objectForKey:@"firstkey"]); 13 14 // 计算字典的元素个数(一个键值对为一个元素)、输出某个键对应的值 15 NSLog(@"%lu,%@",[dicc count], [dicc objectForKey:@"secondkey"]); 16 17 18 // 使用数组存放有相同值的key 19 NSArray * arrayLastOut = [dicc allKeysForObject:@"threevalue"]; 20 NSLog(@"%@",arrayLastOut);
可变字典:
1 //------------------可变字典------------------ 2 // 创建一个空的可变字典 3 NSMutableDictionary *mDic = [[NSMutableDictionary alloc]initWithCapacity:10]; 4 5 // 创建一个可变字典并赋初值 6 NSMutableDictionary * mDicc = [NSMutableDictionary dictionaryWithObjectsAndKeys: @"onevalue", @"firstkey", @"twovalue", @"secondkey", @"threevalue", @"thirdkey", @"threevalue", @"forthkey", nil]; 7 8 // 把一个字典的全部值赋值给另一个字典 9 [mDic addEntriesFromDictionary:mDicc]; 10 11 NSLog(@"%@", mDic); 12 13 // 使用set更新字典中某个key对应的值,如果key存在,则更新value值 14 [mDic setValue: @"changeonevalue" forKey: @"firstkey"]; 15 NSLog(@"%@", mDic); 16 17 // 如果key值不存在,则增加一对key-value键值对 18 [mDic setValue:@"newvalue" forKey:@"fifthkey"]; 19 NSLog(@"%@", mDic); 20 21 // 完全替换成后面的字典内容 22 [mDicc setDictionary:dic]; 23 NSLog(@"%@", mDicc); 24 25 26 // 删除字典中的内容--删除1个 27 [mDicc removeObjectForKey:@"firstkey"]; 28 29 // 删除多个 30 [mDicc removeObjectsForKeys:@[@"firstkey",@"secondkey"]]; 31 32 // 删除全部内容 33 [mDicc removeAllObjects]; 34 NSLog(@"%@", mDicc);
字典遍历:
1 // 字典遍历 2 // 字典遍历方法1 3 for (int x=0; x<mDicc.count; x++) { 4 NSLog(@"%@",[mDicc objectForKey:[[mDicc allKeys] objectAtIndex:x]]); 5 } 6 7 // 字典遍历方法2 8 for (int x=0; x<mDicc.count; x++) { 9 NSLog(@"%@",[[mDicc allValues] objectAtIndex:x]); 10 } 11 12 // 字典遍历方法3 13 for (id key in mDicc) { 14 NSLog(@"%@",[mDicc objectForKey:key]); 15 } 16 17 // 字典遍历方法4 18 id dicx; 19 NSEnumerator *dicEnu = [mDicc keyEnumerator]; 20 while (dicx=[dicEnu nextObject]) { 21 NSLog(@"%@",[mDicc objectForKey:dicx]); 22 } 23 24 // 字典遍历方法5 25 id dicenu; 26 NSEnumerator * dicEnum = [mDicc objectEnumerator]; 27 while (dicenu=[dicEnum nextObject]) { 28 NSLog(@"ddd%@",dicenu); 29 }
标签:
原文地址:http://www.cnblogs.com/jiwangbujiu/p/5313101.html