我有一个包含NSMutableArray
个对象的NSIndexPath
,我希望按照row
按升序对它们进行排序。
最简单/最简单的方法是什么?
这是我尝试过的:
[self.selectedIndexPaths sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSIndexPath *indexPath1 = obj1;
NSIndexPath *indexPath2 = obj2;
return [@(indexPath1.section) compare:@(indexPath2.section)];
}];
答案 0 :(得分:13)
你说你想按row
排序,但你比较section
。此外,section
为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;
}];
答案 1 :(得分:9)
您还可以使用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]];
简单&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}