我在 NSMutableArray 中有一组字典。现在我想按时间升序和降序排序这是我的数组值。
(
{
StartTime = "09:00 AM";
TravelsName = "ABC Travels";
},
{
StartTime = "07:30 AM";
TravelsName = "XYZ Travels ";
},
{
StartTime = "06:45 PM";
TravelsName = "GSP Travels";
},
{
StartTime = "05:00 PM";
TravelsName = "Madura Travels";
},
{
StartTime = "12:45 AM";
TravelsName = "MJT Travels";
},
{
StartTime = "12:45 PM";
TravelsName = "OPR Travels";
},
{
StartTime = "01:00 AM";
TravelsName = "VMS Travels";
}
)
请帮助我,我已经对 NSMutableArray 中的 NSDate 集进行了排序 通过下面的代码
//To sort the Time Array
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat"hh:mm a"];
NSMutableArray *dates = [NSMutableArray arrayWithCapacity:times.count];
for (NSString *timeString in times)
{
NSDate *date = [dateFormatter dateFromString:timeString];
[dates addObject:date];
}
[dates sortUsingSelectorselector(compare];
NSMutableArray *sortedTimes = [NSMutableArray arrayWithCapacity:dates.count];
for (NSDate *date in dates)
{
NSString *timeString = [dateFormatter stringFromDate:date];
[sortedTimes addObject:timeString];
}
但我不知道如何对 NSMutableArray 中的字典进行排序帮助我。
最好使用 NSArray
中已经提供的排序方法。应该这样做:
NSArray *stortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *_Nonnull obj1, NSDictionary *_Nonnull obj2) {
return [obj1[@"StartTime"] comparebj2[@"StartTime"]];
}];
或者如果 StartTime
仍然是一个字符串:
NSArray *stortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *_Nonnull obj1, NSDictionary *_Nonnull obj2) {
return [[dateFormatter dateFromStringbj1[@"StartTime"]] compare:[dateFormatter dateFromStringbj2[@"StartTime"]]];
}];
要更改升序/降序,您只需在 block 中使用时交换 obj1
和 obj2
:
return [obj2[@"StartTime"] comparebj1[@"StartTime"]];
关于ios - 如何在ios中的NSMutableArray中对时间进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33779272/
欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) | Powered by Discuz! X3.4 |