how to sort the time in a NSMutableArray in ios

拥有回忆 提交于 2019-12-06 12:19:32

It is best to use the sorting methods that are already provided in NSArray. Something like this should do:

NSArray *stortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *_Nonnull obj1, NSDictionary *_Nonnull obj2) {
        return [obj1[@"StartTime"] compare:obj2[@"StartTime"]];
}];

Or if the StartTime is still a string:

NSArray *stortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *_Nonnull obj1, NSDictionary *_Nonnull obj2) {
    return [[dateFormatter dateFromString:obj1[@"StartTime"]] compare:[dateFormatter dateFromString:obj2[@"StartTime"]]];
}];

To change the ascending/descending order you simply swap the obj1 and obj2 when used in the block:

return [obj2[@"StartTime"] compare:obj1[@"StartTime"]];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!