NSArray *array = @[@{
@"month":@"Dec",
@"year": @"2017",
},
@{
@"month":@"Oct",
@"year": @"2017",
},
@{
@"month":@"Jan",
@"year": @"2018",
}];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMM"];
NSArray *sorted = [array sortedArrayUsingComparator:^NSComparisonResult(NSDictionary * _Nonnull dict1, NSDictionary * _Nonnull dict2) {
NSDate *date1 = [dateFormatter dateFromString:dict1[@"month"]];
NSDateComponents *components1 = [[NSCalendar currentCalendar] components:NSCalendarUnitMonth fromDate:date1];
[components1 setYear:[dict1[@"year"] integerValue]];
NSDate *date2 = [dateFormatter dateFromString:dict2[@"month"]];
NSDateComponents *components2 = [[NSCalendar currentCalendar] components:NSCalendarUnitMonth fromDate:date2];
[components2 setYear:[dict2[@"year"] integerValue]];
NSDate *finalDate1 = [[NSCalendar currentCalendar] dateFromComponents:components1];
NSDate *finalDate2 = [[NSCalendar currentCalendar] dateFromComponents:components2];
return [finalDate1 compare:finalDate2];
}];
NSLog(@"Sorted: %@", sorted);
输出:
$>Sorted: (
{
month = Oct;
year = 2017;
},
{
month = Dec;
year = 2017;
},
{
month = Jan;
year = 2018;
}
)
那么逻辑是什么呢?
你不能用一个简单的
NSSortDescriptor
所以你需要创建一个
NSDate
这可以简单地进行比较。
如果需要,可以将该日期保存在数组的字典中,或者使用
sortedArrayUsingComparator:
用一个积木。
要颠倒顺序,最简单的方法是:
return [finalDate1 compare:finalDate2];
或
return [finalDate2 compare:finalDate1];
注:施工方式
finalDate1
/
finalDate2
可能不是最佳选择。