Sorting array based on date and time with two dictionary keys

空扰寡人 提交于 2019-12-04 19:45:47

You need to sort the times as well, that is why sortUsingDescriptors: takes an array.

-(NSMutableArray *)sortArrayBasedOndate:(NSMutableArray *)arraytoSort
{
    NSDateFormatter *fmtDate = [[NSDateFormatter alloc] init];
    [fmtDate setDateFormat:@"yyyy-MM-dd"];

    NSDateFormatter *fmtTime = [[NSDateFormatter alloc] init];
    [fmtTime setDateFormat:@"HH:mm"];

    NSComparator compareDates = ^(id string1, id string2)
    {
        NSDate *date1 = [fmtDate dateFromString:string1];
        NSDate *date2 = [fmtDate dateFromString:string2];

        return [date1 compare:date2];
    };

    NSComparator compareTimes = ^(id string1, id string2)
    {
        NSDate *time1 = [fmtTime dateFromString:string1];
        NSDate *time2 = [fmtTime dateFromString:string2];

        return [time1 compare:time2];
    };

    NSSortDescriptor * sortDesc1 = [[NSSortDescriptor alloc] initWithKey:@"start_date" ascending:YES comparator:compareDates];
    NSSortDescriptor * sortDesc2 = [NSSortDescriptor sortDescriptorWithKey:@"starts" ascending:YES comparator:compareTimes];
    [arraytoSort sortUsingDescriptors:@[sortDesc1, sortDesc2]];

    return arraytoSort;
}

Concatenate both to one timestamp. Then get the TimeInterVal since ref date, and sort by this number

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