对NSIndexPaths数组进行排序

Eri*_*ric 12 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)];
}];
Run Code Online (Sandbox Code Playgroud)

das*_*ght 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;
}];
Run Code Online (Sandbox Code Playgroud)


So *_* It 10

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

如果self.selectedIndexPath是不可变的:

NSSortDescriptor *rowDescriptor = [[NSSortDescriptor alloc] initWithKey:@"row" ascending:YES];
NSArray *sortedRows = [self.selectedIndexPaths sortedArrayUsingDescriptors:@[rowDescriptor]];
Run Code Online (Sandbox Code Playgroud)

或者如果self.selectedIndexPathNSMutableArray,简单地说:

NSSortDescriptor *rowDescriptor = [[NSSortDescriptor alloc] initWithKey:@"row" ascending:YES];
[self.selectedIndexPaths sortedArrayUsingDescriptors:@[rowDescriptor]];
Run Code Online (Sandbox Code Playgroud)

简单而简短.


Ant*_*ony 8

对于可变数组:

[self.selectedIndexPaths sortUsingSelector:@selector(compare:)];
Run Code Online (Sandbox Code Playgroud)

对于不可变数组:

NSArray *sortedArray = [self.selectedIndexPaths sortedArrayUsingSelector:@selector(compare:)]
Run Code Online (Sandbox Code Playgroud)