Sort Array of Dictionaries by NSDate

前端 未结 3 433
北海茫月
北海茫月 2021-01-01 03:05

I have an array of dictionaries. Within each dictionary, there is a a key dateOfInfo (an NSDate) and several other things. I want to sort the array

3条回答
  •  轮回少年
    2021-01-01 03:27

    try like this,

                NSDateFormatter *fmtDate = [[NSDateFormatter alloc] init];
                 [fmtDate setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
                 NSComparator compareDates = ^(id string1, id string2)
                 {
                     NSDate *date1 = [fmtDate dateFromString:string1];
                     NSDate *date2 = [fmtDate dateFromString:string2];
    
                     return [date1 compare:date2];
                 };
                 NSSortDescriptor * sortDesc1 = [[NSSortDescriptor alloc] initWithKey:@"StartTime" ascending:YES comparator:compareDates];
                 [youArray sortUsingDescriptors:@[sortDesc1]];
    

提交回复
热议问题