我想根据日期参数对以下数组进行排序,但问题是来自一个服务器,我没有获得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而不是在NSDate或NSTimeInterval
[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;
}];
我假设您有一个特定的理由来保持数据的原样,而不是解析到模型类中,保持它的方便性。
在您的场景中,您可以尝试使用以下代码对数组进行排序:
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;
}
)
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。