标签:
#import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { //NSDictionary字典对象,字典主要特征是一对一的key和value组成 //不可变字典 //初始化字典,一半key值是字符串对象,控制用NSNull对象表示 NSDictionary *dic1 = [NSDictionary dictionaryWithObject:@"velue1" forKey:@"key1"]; NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:@"value2",@"key2",@"value3",@"key3",nil]; NSDictionary *dic3 = [NSDictionary dictionaryWithDictionary:dic1]; //值与键都为数组,需要注意的是value数组与key数组的元素个数要保持一致,因为字典都是键值对,要一一对应,nil不会计入字典数量中 NSArray *arrValue = [NSArray arrayWithObjects:@"hello",@"world",@"!",@"test", nil]; NSArray *arrKey = [NSArray arrayWithObjects:@"keyOne",@"keyTow",@"keyThree",@"keytest", nil]; NSDictionary *dic4 = [NSDictionary dictionaryWithObjects:arrValue forKeys:arrKey]; NSLog(@"%@",dic2); NSLog(@"%@",dic3); NSLog(@"%@",dic4); //获取字典的数量 NSInteger count = [dic4 count]; NSLog(@"%ld",count); //通过key获取value值 NSObject *objNew = [dic2 objectForKey:@"key2"]; NSLog(@"%@",objNew); NSObject *objtest = [dic4 objectForKey:@"keyOne"]; NSLog(@"---------%@",objtest); //通过数组中的key匹配字典 NSArray * test = [NSArray arrayWithObjects:@"keyOne",@"keyThree", nil]; NSObject *objNew1 = [dic4 objectsForKeys:test notFoundMarker:@"error"]; NSLog(@"%@",objNew1); //将字典的key变成一个枚举对象用于遍历 NSEnumerator *enumerator = [dic4 keyEnumerator]; //枚举遍历法(keyEnumerator) id key = [enumerator nextObject]; while (key) { id object = [dic4 objectForKey:key]; NSLog(@"%@",object); key = [enumerator nextObject];//不复写key的值,会陷入死循坏 } //获取字典所有key集合 NSArray *arrKey1 = [dic2 allKeys]; NSLog(@"%@",arrKey1); //获取字典所有value集合 NSArray *arrValue1 = [dic2 allValues]; NSLog(@"%@",arrValue1); //可变字典 //初始化可变字典 NSMutableDictionary *mudic1 = [NSMutableDictionary dictionary]; NSLog(@"%@",mudic1);//为空 NSMutableDictionary *mudic2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"v1",@"k1",@"v2",@"k2", nil]; //把一个字典加入到另一个字典中(把mudic2添加到mudic1中) [mudic1 addEntriesFromDictionary:mudic2]; NSLog(@"%@",mudic1); //给字典新添增元素 [mudic1 setObject:@"Augus" forKey:@"key1"]; NSLog(@"%@",mudic1); //把一个字典的内容设置为跟另一个字典内容相同(把mudic1的内容设置为mudic2一样) [mudic1 setDictionary:mudic2]; NSLog(@"%@",mudic1); //移除字典元素 [mudic1 removeObjectForKey:@"k2"]; NSLog(@"%@",mudic1); //快速遍历方法 for (id key in mudic2) { id objx = [mudic2 objectForKey:key]; NSLog(@"%@",objx); } //常用遍历方法,首先获取到key的集合,然后通过遍历key集合来实现字典value的遍历 NSArray *keyarr = [mudic2 allKeys]; NSInteger num = [keyarr count]; for (int i=0; i<num; i++) { id keyx = [keyarr objectAtIndex:i]; id valuex = [mudic2 objectForKey:keyx]; NSLog(@"%@",valuex); } } return 0; }
标签:
原文地址:http://www.cnblogs.com/mir-augus/p/5090456.html