NSArray of Dates sort

前端 未结 2 906
遇见更好的自我
遇见更好的自我 2021-01-21 05:52

Consider this array. It has no keys, so I am not sure I can use NSSortDescriptor. What would be the best method to sort them?

(
    \"Thursday, July 30, 2009\"         


        
相关标签:
2条回答
  • 2021-01-21 06:38

    You can use sortedArrayUsingFunction:

    Here's some example code.

    NSInteger dateSort(id s1, id s2, void *context)
    {
        NSDateFormatter* format = (NSDateFormatter*)context;
        NSDate* d1 = [format dateFromString:s1];
        NSDate* d2 = [format dateFromString:s2];
    
        return [d1 compare:d2];
    }
    
    ...
    
    -(void)someObjectiveCMethod
    {
        NSDateFormatter* format = [[[NSDateFormatter alloc] init] autorelease];
    
        // Find theses format codes here:
        // http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
        //
        [format setDateFormat:@"EEEE, MMMM dd, yyyy"];
    
        NSArray* myArray = getMyArray();
        NSArray* sortedArray = [myArray sortedArrayUsingFunction:dateSort context:format];
    }
    

    There are a number of these sorts of sort methods in NSArray. It's worth looking at those to familiarize yourself with them.

    0 讨论(0)
  • 2021-01-21 06:42
    NSArray * unsortedDates = ...;
    NSArray * sortedDates = [unsortedDates sortedArrayUsingSelector:@selector(compare:)];
    
    0 讨论(0)
提交回复
热议问题