将包含日期的字典的 NSArray 排序为字符串

Sorting NSArray of Dictionary containing Date as String

我想根据日期参数对以下数组进行排序,但问题出在服务器上,我没有得到 timestamp,我得到的日期是 string,任何人都可以吗请帮忙

    NSArray *array = @[
        @{@"valid":@"Y",@"mof":@"ON",@"dof":@"17-05-2019",@"rtntype":@"CODE1",@"ret_prd":@"042019"},
        @{@"valid":@"Y",@"mof":@"ON",@"dof":@"19-04-2019",@"rtntype":@"CODE1",@"ret_prd":@"032019"},
        @{@"valid":@"Y",@"mof":@"ON",@"dof":@"19-04-2019",@"rtntype":@"CODE2",@"ret_prd":@"032019"}
    ];

我尝试应用该解决方案,但它不起作用,因为我们的日期在 NSString 而不是 NSDateNSTimeInterval

    [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {

        if ([obj1 intValue] == [obj2 doubleValue])
            return NSOrderedSame;

        else if ([obj1 intValue] < [obj2 doubleValue])
            return NSOrderedAscending;

        else
            return NSOrderedDescending;

    }];

我假设您有特定的原因要按原样保留数据而不是解析到模型中 class 将其放在手边。

在您的场景中,您可以尝试使用以下代码对数组进行排序:

NSArray *array = @[
        @{@"valid":@"Y",@"mof":@"ON",@"dof":@"19-04-2019",@"rtntype":@"CODE1",@"ret_prd":@"032019"},
        @{@"valid":@"Y",@"mof":@"ON",@"dof":@"17-05-2019",@"rtntype":@"CODE1",@"ret_prd":@"042019"},
        @{@"valid":@"Y",@"mof":@"ON",@"dof":@"19-04-2019",@"rtntype":@"CODE2",@"ret_prd":@"032019"}
    ];

    //NSDateFormatter to convert NSString to NSDate
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd-MM-yyyy"];

    NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        if ([obj1 isKindOfClass:[NSDictionary class]]
            && [obj2 isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dict1 = (NSDictionary *)obj1;
            NSDictionary *dict2 = (NSDictionary *)obj2;
            if ([dict1[@"dof"] isKindOfClass:[NSString class]]
                && [dict2[@"dof"] isKindOfClass:[NSString class]]) {
                NSString *dof1 = (NSString *) dict1[@"dof"];
                NSString *dof2 = (NSString *) dict2[@"dof"];
                NSDate *date1 = [formatter dateFromString:dof1];
                NSDate *date2 = [formatter dateFromString:dof2];
                return [date1 compare:date2];//Update the return based on in which order you want the resulting array
            }
        }
        return NSOrderedSame;
    }];
    NSLog(@"%@", sortedArray);

结果是:

(
        {
        dof = "19-04-2019";
        mof = ON;
        "ret_prd" = 032019;
        rtntype = CODE1;
        valid = Y;
    },
        {
        dof = "19-04-2019";
        mof = ON;
        "ret_prd" = 032019;
        rtntype = CODE2;
        valid = Y;
    },
        {
        dof = "17-05-2019";
        mof = ON;
        "ret_prd" = 042019;
        rtntype = CODE1;
        valid = Y;
    }
)