iOS 字典根据key排序

2024-01-23  本文已影响0人  那一处风景ljz
"list": [
            {
                "d_id": "603912913ce90e276a84",
                "a_id": 9063,
                "a_t": 2024-01-16
            },
            {
                "d_id": "19404a13c8478c1e4151",
                "a_id": 9002,
                "a_t": 2024-01-17
            },
            {
                "d_id": "697189647cb94cb07f91",
                "a_id": 7,
                "a_t": 2024-01-16
            }
        ]

需求:把"a_t"对应的值相同的字典对象组成一个数组,并对list数组中各字典依据key值"a_t"进行排序。

for (NSDictionary *tempDic in [infoDic objectForKey:@"list"]) {
            L_JingGaoModel *model = [L_JingGaoModel modelWithDictionary:tempDic];
            [tempArray addObject:model];
            [self.dataArray addObject:model];
            
            NSInteger ttttt = [model.ts integerValue];
            NSString *dateStr = [self timestampSwitchDateString:ttttt andFormatter:@"YYYY-MM-dd"];
            
            if (!self.dataDic[dateStr]) {
                self.dataDic[dateStr] = [NSMutableArray array];
            }
            [self.dataDic[dateStr] addObject:model];
        }

MyLog(@"ts----  ----  %@",self.dataDic);
/**
 对字典(Key-Value)排序 区分大小写
 @param dict 要排序的字典
 */
- (void)sortedDictionary:(NSMutableDictionary *)dict{
    
    //将所有的key放进数组
    NSArray *allKeyArray = [dict allKeys];
    //序列化器对数组进行排序的block 返回值为排序后的数组
    NSArray *afterSortKeyArray = [allKeyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        NSComparisonResult resuest = [obj2 compare:obj1];//降序
        return resuest;
    }];
    //NSLog(@"afterSortKeyArray:%@",afterSortKeyArray);
    self.keyArr = [[NSMutableArray alloc] initWithArray:afterSortKeyArray];
    
    //通过排列的key值获取value
    NSMutableArray *valueArray = [NSMutableArray array];
    for (NSString *sortsing in afterSortKeyArray) {
        NSString *valueString = [dict objectForKey:sortsing];
        [valueArray addObject:valueString];
    }
    
    //NSLog(@"valueArray:%@",valueArray);
    self.valueArr = [valueArray mutableCopy];
}
15241705481749_.pic.jpg
上一篇下一篇

猜你喜欢

热点阅读