13

我有一个NSMutableArray包含NSIndexPath对象的对象,我想按它们row的升序对它们进行排序。

最短/最简单的方法是什么?

这是我尝试过的:

[self.selectedIndexPaths sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSIndexPath *indexPath1 = obj1;
    NSIndexPath *indexPath2 = obj2;
    return [@(indexPath1.section) compare:@(indexPath2.section)];
}];
4

4 回答 4

13

你说你想排序row,但你比较section。此外,sectionis NSInteger,因此您不能在其上调用方法。

修改您的代码如下排序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;
}];
于 2013-02-18T03:02:13.913 回答
10

您还可以使用 NSSortDescriptors 来按 'row' 属性对 NSIndexPath 进行排序。

如果self.selectedIndexPath是不可变的:

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

或者如果self.selectedIndexPath是 a NSMutableArray,简单地说:

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

简单而简短。

于 2013-06-18T12:36:13.030 回答
8

对于可变数组:

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

对于不可变数组:

NSArray *sortedArray = [self.selectedIndexPaths sortedArrayUsingSelector:@selector(compare:)]
于 2014-06-13T14:55:47.227 回答
3

迅速:

let paths = tableView.indexPathsForSelectedRows() as [NSIndexPath]
let sortedArray = paths.sorted {$0.row < $1.row}
于 2014-10-30T14:01:14.953 回答