13

I have an NSMutableArray that contains NSIndexPath objects, and I'd like to sort them by their row, in ascending order.

What's the shortest/simplest way to do it?

This is what I've tried:

[self.selectedIndexPaths sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSIndexPath *indexPath1 = obj1;
    NSIndexPath *indexPath2 = obj2;
    return [@(indexPath1.section) compare:@(indexPath2.section)];
}];
Eric
  • 16,003
  • 15
  • 87
  • 139

4 Answers4

13

You said that you would like to sort by row, yet you compare section. Additionally, section is NSInteger, so you cannot call methods on it.

Modify your code as follows to sort on the row:

[self.selectedIndexPaths sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSInteger r1 = [obj1 row];
    NSInteger r2 = [obj2 row];
    if (r1 > r2) {
        return (NSComparisonResult)NSOrderedDescending;
    }
    if (r1 < r2) {
        return (NSComparisonResult)NSOrderedAscending;
    }
    return (NSComparisonResult)NSOrderedSame;
}];
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
10

You can also use NSSortDescriptors to sort NSIndexPath by the 'row' property.

if self.selectedIndexPath is non-mutable:

NSSortDescriptor *rowDescriptor = [[NSSortDescriptor alloc] initWithKey:@"row" ascending:YES];
NSArray *sortedRows = [self.selectedIndexPaths sortedArrayUsingDescriptors:@[rowDescriptor]];

or if self.selectedIndexPath is a NSMutableArray, simply:

NSSortDescriptor *rowDescriptor = [[NSSortDescriptor alloc] initWithKey:@"row" ascending:YES];
[self.selectedIndexPaths sortedArrayUsingDescriptors:@[rowDescriptor]];

Simple & short.

So Over It
  • 3,668
  • 3
  • 35
  • 46
8

For a mutable array:

[self.selectedIndexPaths sortUsingSelector:@selector(compare:)];

For an immutable array:

NSArray *sortedArray = [self.selectedIndexPaths sortedArrayUsingSelector:@selector(compare:)]
lobianco
  • 6,226
  • 2
  • 33
  • 48
3

In swift:

let paths = tableView.indexPathsForSelectedRows() as [NSIndexPath]
let sortedArray = paths.sorted {$0.row < $1.row}
Eugene Braginets
  • 856
  • 6
  • 16