今天再把NSDictionary的一些方法归归类,做一个工具博客出来。
NSDictionary
一:NSDictionary的初始化
NSDictionary *dic = @{@"name":@"lilei",@"age":@"13"};
NSDictionary *dic1 = [NSDictionary new];
NSDictionary *dic2 = [[NSDictionary alloc]initWithDictionary:dic1];
NSDictionary *dic3 = [[NSDictionary alloc]initWithObjectsAndKeys:@"lilei",@"name",@"13",@"age", nil];
NSArray *keyArray = @[@"name",@"age"];
NSArray *valueArray = @[@"lilei",@"13"];
NSDictionary *dic4 = [[NSDictionary alloc]initWithObjects:valueArray forKeys:keyArray];
二:NSDictionary的属性
NSDictionary *dic = @{@"name":@"lilei",@"age":@"13"};
NSInteger count = dic.count; // 字典里键值对的个数
NSArray *allKeys = dic.allKeys; // 字典里的所有键
NSArray *allValues = dic.allValues; // 字典里的所有值
NSString *description = dic.description; // 字典的描述字符串
三:NSDictionary的一些常用方法
1:返回字典内一个值对应的所有键
NSDictionary *dic = @{@"name":@"lilei",@"age":@"13",@"class":@"13"};
NSArray *array = [dic allKeysForObject:@"13"];
返回的array是 @[@"age",@"class"];
2:是否完全与另一个字典相同
NSDictionary *dic1 = @{@"name":@"lilei",@"age":@"13",@"class":@"13"};
NSDictionary *dic2 = @{@"name":@"lilei",@"age":@"13",@"class":@"13"};
BOOL isSame = [dic1 isEqualToDictionary:dic2];
返回YES
3:使用block来遍历字典的键值对
NSDictionary *dic1 = @{@"name":@"lilei",@"age":@"13",@"class":@"13"};
[dic1 enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
// 遍历字典的所有键值对
}];
[dic1 enumerateKeysAndObjectsWithOptions:NSEnumerationReverse usingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
// 倒序遍历字典的所有键值对
}];
4:让字典按照value的大小顺序来对keys键值进行排序
NSDictionary *dic1 = [NSDictionary dictionaryWithObjectsAndKeys:@"4",@"A",@"6",@"C",@"5",@"B",nil];
NSArray *array = [dic1 keysSortedByValueUsingSelector:@selector(compare:)];
NSLog(@"排序键值对%@",array);
array的值为 @[@"A",@"B",@"C"];
跟NSArray一样,有Function【函数】,Comparator【比较】,Selector【选择器】几种方式来进行排序
NSMutableDictionary
1:讲一个字典中的所有属性新增到可变字典中
NSDictionary *dic1 = @{@"name":@"lilei",@"age":@"13",@"class":@"13"};
NSMutableDictionary *mDic = [NSMutableDictionary new];
[mDic addEntriesFromDictionary:dic1];
2:从可变字典中移除键值对
NSDictionary *dic1 = @{@"name":@"lilei",@"age":@"13",@"class":@"13"};
NSMutableDictionary *mDic = [[NSMutableDictionary alloc]initWithDictionary:dic1];
[mDic removeObjectForKey:@"name"]; // 移除name的键值对
[mDic removeAllObjects]; // 移除所有键值对
3:修改或新增可变数组的键值对【如果新增的键值对本来就有,则修改否则新增】
NSDictionary *dic1 = @{@"name":@"lilei",@"age":@"13",@"class":@"13"};
NSMutableDictionary *mDic = [[NSMutableDictionary alloc]initWithDictionary:dic1];
[mDic setObject:@"hanmeimei" forKey:@"name"]; // 更新了原有的name键值对
[mDic setObject:@"color" forKey:@"white"]; // 新增了值为white的color键值对