Sort Array of Dictionaries by NSDate

前端 未结 3 343
北海茫月
北海茫月 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:20

    You can sort using NSSortDescription, e.g.

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey: @"dateOfInfo" ascending: NO];
    NSArray *sortedArray = [array sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
    [sortDescriptor release];
    

    You can also use the method

    - (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context
    
    0 讨论(0)
  • 2021-01-01 03:26

    The basic bubble sorting algorithm would work. In this case you need to loop through your array, use valueForKey message on [array objectAtIndex:] to get the NSDate values. For comparing dates see this post . So if you are sorting in ascending order of date, just add the object with the lower date (remember bubble sort comparisons?) to an array which will hold your sorted result.

    0 讨论(0)
  • 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]];
    
    0 讨论(0)
提交回复
热议问题