2013-02-18 44 views
12

我有一個NSMutableArray包含NSIndexPath對象,我想按它們的row按升序對它們進行排序。對NSIndexPaths數組排序

什麼是最短/最簡單的方法呢?

這是我已經試過:

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

回答

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; 
}]; 
+0

謝謝!你搖滾。 – Eric 2013-02-18 03:47:32

9

您還可以使用NSSortDescriptors由「行」屬性進行排序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]]; 

簡單&短。

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} 
+0

是的,在功能語言中排序要短得多。 – kelin 2015-02-25 08:49:26

+2

只有只有一個部分時才能使用 – 2016-09-28 11:31:11