Objective C: Sort Two Dimensional Array

前端 未结 2 364
青春惊慌失措
青春惊慌失措 2021-01-07 10:15

I have an array of arrays. The contained array\'s first elements are all NSDate objects. I would like to sort the array containing the arrays in order from most recent to le

相关标签:
2条回答
  • 2021-01-07 10:20

    If array is mutable and you want to sort it in place:

    [array sortUsingComparator:^(id a, id b) {
        return [b[0] compare:a[0]];
    }];
    

    If array is immutable or you want to leave it alone and make a sorted copy:

    NSArray *sortedArray = [array sortedArrayUsingComparator:^(id a, id b) {
        return [b[0] compare:a[0]];
    }];
    
    0 讨论(0)
  • 2021-01-07 10:40

    This results in an infinite loop because, in every step, you're inserting two more values into the array. Thus your array is growing faster than you are traversing it. I'm assuming you meant to swap the values.

    In any case, a much simpler and more efficient sort is to use the built-in sorting capabilities:

    // NSArray *sortedArray, with the unsorted 'array' pulled from some other instance
    sortedArray = [array sortedArrayUsingComparator:^(id a, id b) {
        return [[b objectAtIndex:0] compare:[a objectAtIndex:0]];
    }];
    
    0 讨论(0)
提交回复
热议问题