对NSIndexPath数组进行排序

13

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

有什么最简单/最短的方法吗?

这是我尝试过的:

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

13

你说你想按 row 进行排序,但你却在比较 section。此外,sectionNSInteger 类型,所以你不能对它调用方法。

请按照以下方式修改你的代码来按 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;
}];

10

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

如果self.selectedIndexPath是不可变的:

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

或者如果self.selectedIndexPath是一个NSMutableArray,只需:

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

简单易懂

8

对于可变数组:

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

对于一个不可变数组:

NSArray *sortedArray = [self.selectedIndexPaths sortedArrayUsingSelector:@selector(compare:)]

3

在Swift中:

let paths = tableView.indexPathsForSelectedRows() as [NSIndexPath]
let sortedArray = paths.sorted {$0.row < $1.row}

是的,在函数式编程语言中,排序要短得多。 - kelin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接