标签:
1.1创建不可变字典
//创建字典 //注意: //1,元素个数是偶数 //2,每两个元素是一个键值对 //3,值在前,键在后 NSDictionary *dic = [[NSDictionary alloc] initWithObjectsAndKeys:@"huang",@"name",@"30",@"age", nil]; NSLog(@"%@",dic); //用一个字典来创建另外一个字典 NSDictionary *dic2 = [[NSDictionary alloc] initWithDictionary:dic]; //注意: //1,value和key的个数要相同 //2,values和keys里面的元素的先后顺序要对应 NSDictionary *dic3 = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:@"huang",@"30", nil] forKeys:[NSArray arrayWithObjects:@"name",@"age", nil]]; NSLog(@"%@",dic3); //创建数组的新方式 NSArray *arr = @[@"1",@"2",@"3"]; NSDictionary *dic4 = [NSDictionary dictionaryWithObjectsAndKeys:@"30",@"age",@"huang",@"name", nil]; NSDictionary *dic5 = [NSDictionary dictionaryWithDictionary:dic4]; NSDictionary *dic6 = [NSDictionary dictionaryWithObjects:@[@"huang",@"30"] forKeys:@[@"name",@"age"]]; //创建字典的新方式 NSDictionary *dic7 = @{@"name": @"huang",@"age":@"30"};
1.2不可变字典的常用操作
//字典的常用操作 NSInteger count = [dic7 count]; NSLog(@"%ld",count); //根据键去获取值 NSString *str = [dic7 valueForKey:@"name"]; NSLog(@"%@",str); //获取所有的key NSArray *allKeys = [dic7 allKeys]; NSLog(@"%@",allKeys); //获取所有的value NSArray *allValues = [dic7 allValues]; //获取一个value对应的key NSDictionary *dic8 = @{@"name":@"huang",@"age":@"15",@"score":@"15"}; NSArray *arr1 = [dic8 allKeysForObject:@"15"]; NSLog(@"%@",arr1); NSDictionary *dic9 = @{@"dic8":dic8,@"dic7":dic7}; NSLog(@"%@",dic9); //数组与字典的嵌套 NSArray *array1 = @[@"1",@"2",@"3"]; NSDictionary *dictionary1 = @{@"name":@"xiaoming",@"age":@"10"}; NSDictionary *dictionary2 = @{@"array":array1,@"dictionary":dictionary1}; NSLog(@"%@",dictionary2); NSArray *array2 = @[array1,dictionary1]; NSLog(@"%@",array2); //字典的遍历 NSDictionary *dictionary3 = @{@"name":@"huang",@"age":@"30",@"number":@"30"}; NSArray *allKeys1 = [dictionary3 allKeys]; for(NSString *key in allKeys1) { NSString *str = [dictionary3 objectForKey:key]; NSLog(@"%@=%@",key,str); }
2.1可变字典的创建与使用
NSDictionary *dic = @{@"name":@"xiaoming",@"age":@"10"}; NSDictionary *dic1 = @{@"age":@"15",@"score":@"30"}; NSMutableDictionary *muDic = [[NSMutableDictionary alloc] init]; //从一个字典内添加元素到可变字典 //注意: //当dic与可变字典有相同的key时,不添加这个key,但是会将key对应的value覆盖。 [muDic addEntriesFromDictionary:dic]; NSLog(@"%@",muDic); [muDic addEntriesFromDictionary:dic1]; NSLog(@"%@",muDic); //添加一个元素 //注意: //1,setObject:forKey: 当key不存在时就是添加元素,当key存在时就是修改元素值 [muDic setObject:@"mingming" forKey:@"nickname"]; [muDic setObject:@"xiaohua" forKey:@"name"]; NSLog(@"%@",muDic); //删除一个元素 [muDic removeObjectForKey:@"name"]; NSLog(@"%@",muDic); //删除一个keys数组里面对应的所有元素 [muDic removeObjectsForKeys:@[@"nickname",@"aaa"]]; NSLog(@"%@",muDic); //删除字典内的所有元素 [muDic removeAllObjects]; NSLog(@"%@",muDic); //修改字典 [muDic setDictionary:dic]; NSLog(@"%@",muDic);
标签:
原文地址:http://www.cnblogs.com/DWdan/p/5062148.html