2009-12-21 102 views
20

我有一个NSString对象数组,我必须按降序排序。排序数组(NSArray)降序

因为我没有找到任何API按降序对数组进行排序,所以我按照以下方式进行了处理。

我为NSString编写了一个类别,如下所列。

- (NSComparisonResult)CompareDescending:(NSString *)aString 
{ 

    NSComparisonResult returnResult = NSOrderedSame; 

    returnResult = [self compare:aString]; 

    if(NSOrderedAscending == returnResult) 
     returnResult = NSOrderedDescending; 
    else if(NSOrderedDescending == returnResult) 
     returnResult = NSOrderedAscending; 

    return returnResult; 
} 

然后我排序利用声明

NSArray *sortedArray = [inFileTypes sortedArrayUsingSelector:@selector(CompareDescending:)]; 

这是正确的解决方案的阵列?有更好的解决方案吗?

回答

54

您可以使用NSSortDescriptor:

NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO selector:@selector(localizedCompare:)]; 
NSArray* sortedArray = [inFileTypes sortedArrayUsingDescriptors:@[sortDescriptor]]; 

这里我们使用localizedCompare:比较字符串,并通过NO至升:选项降序排序。

+0

因为 'sortDescriptorWithKey' 10.6 aboveI已经使用下面的语句。 [[NSSortDescriptor alloc] initWithKey:nil升序:NO]; 谢谢... – 2009-12-21 10:26:17

+0

的确,我应该提到 - 不要忘了-autorelease虽然:) – 2009-12-21 10:45:22

+0

Works awesome!Thanks! – 2013-10-11 06:46:09

4
NSSortDescriptor *sortDescriptor; 
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"length" ascending:NO]; 
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; 
[wordsArray sortUsingDescriptors:sortDescriptors]; 

使用此代码我们可以按照长度降序排列数组。

2

或简化您的解决方案:

NSArray *temp = [[NSArray alloc] initWithObjects:@"b", @"c", @"5", @"d", @"85", nil]; 
NSArray *sortedArray = [temp sortedArrayUsingComparator: 
         ^NSComparisonResult(id obj1, id obj2){ 
          //descending order 
          return [obj2 compare:obj1]; 
          //ascending order 
          return [obj1 compare:obj2]; 
         }]; 
NSLog(@"%@", sortedArray);