对NSIndexPaths数组进行排序

时间:2013-02-18 02:53:01

标签: nsmutablearray nsindexpath

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

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

这是我尝试过的:

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

4 个答案:

答案 0 :(得分: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;
}];

答案 1 :(得分:9)

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

如果self.selectedIndexPath不可变:

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

或如果self.selectedIndexPathNSMutableArray,只需:

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

简单&amp;短。

答案 2 :(得分:8)

对于可变数组:

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

对于不可变数组:

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

答案 3 :(得分:3)

在swift:

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