-NSDictionary
1. NSDictionary 创建
//创建value1,key1,value2,key2...(key和value成对出现)
//其中value可以是任意的OC对象
NSDictionary *dict1 = [NSDictionary dictionaryWithObjectsAndKeys:@"one",@"@1",@"two",@"2",@"three",@"3", nil];
NSLog(@"%@",dict1);// { 1 = one; 2 = two; 3 = three; }
// @{ key1:value1 , key2:value , ...} 方法创建,只能创建不可变字典
NSDictionary *dict2 =@{@"4":@"four" , @"5":@"five" , @"6":@"six" , @"7":@"five" };
NSLog(@"%@",dict2); //{ 4 = four; 5 = five; 6 = six; }
2. 通过key访问value
objectForKey: 和 valueForKey: 在多数情况下都是一样的结果返回,有个例外就是如果 key 是以 @ 开头,valueForKey: 就会报错,建议在 NSDictionary 下用 objectForKey: 来取值。
NSString *valueStr1 = [dict1 valueForKey:@"@1"]; //报错
NSString *valueStr2 = [dict1 objectForKey:@"@1"]; //正常
NSLog(@"%@",valueStr2); // one
NSString *valueStr3 = dict1[@"2"];
NSLog(@"%@",valueStr3); // two
3. 遍历字典,遍历key值
NSArray *keyArr = [dict1 allKeys];
NSLog(@"%@",keyArr); //(2,@1,3) (字典中的key顺序不一定是存储时的顺序)
4. 获取具有相同value的key
NSArray *keyArr1 = [dict2 allKeysForObject:@"five"];
NSLog(@"%@",keyArr1); // (5,7)
5.遍历value
NSArray *valueArr = [dict2 allValues];
NSLog(@"%@",valueArr); // (six,four,five,five)
6.默认遍历key
for(id obj in dict1){
NSLog(@"%@",obj);
} //2 @1 3
-NSMutableDictionary
1.创建空的可变字典
NSMutableDictionary *mDict1 = [[NSMutableDictionary alloc]init];
NSMutableDictionary *mDict2 = [NSMutableDictionary dictionary];
2.用数组实例化可变字典
NSMutableDictionary *mDict3 = [NSMutableDictionary dictionaryWithObjects:@[@"one",@"two",@"three",@"four"] forKeys:@[@"1",@"2",@"3",@"4",]];
NSLog(@"%@" , mDict3); //{ 1 = one ; 2 = two ; 3 = three ; 4 = four ; }
3.添加key-value 或者 修改key-value 均可用setObject方法
[mDict3 setObject:@"five" forKey:@"5"]; //当key不存在时,视为添加key-value
[mDict3 setObject:@"newOne" forKey:@"1"]; //当key存在时, 视为修改key-value
NSLog(@"%@",mDict3);//{ 1 = newOne; 2 = two; 3 = three; 4 = four; 5 = five; }
4.删除键值对
[mDict3 removeObjectForKey:@"2"];
NSLog(@"%@",mDict3);// { 1 = newOne; 3 = three; 4 = four; 5 = five; }
5.删除字典中所有含有目标key的键值对
[mDict3 removeObjectsForKeys:@[@"3",@"4"]];
NSLog(@"%@",mDict3);// { 1 = newOne; 5 = five; }
6.删除所有键值对
[mDict3 removeAllObjects];
NSLog(@"%@",mDict3);//{ }