【问题标题】:Sorting array(NSArray) in descending order按降序排序数组(NSArray)
【发布时间】:2009-12-21 08:50:58
【问题描述】:

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

由于我没有找到任何 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:)];

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

【问题讨论】:

    标签: objective-c cocoa


    【解决方案1】:

    你可以使用 NSSortDescriptor:

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

    这里我们使用localizedCompare:比较字符串,并将NO传递给升序:降序排序选项。

    【讨论】:

    • 自从 'sortDescriptorWithKey' 10.6 以上我使用了以下语句。 [[NSSortDescriptor alloc] initWithKey: nil 升序: NO];谢谢...
    • 确实,我应该提到这一点——不过不要忘记 -autorelease :)
    • 效果很好!谢谢!
    【解决方案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);
    

    【讨论】:

      【解决方案3】:
      NSSortDescriptor *sortDescriptor; 
      sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"length" ascending:NO];
      NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
      [wordsArray sortUsingDescriptors:sortDescriptors];
      

      使用此代码,我们可以根据长度对数组进行降序排序。

      【讨论】:

        猜你喜欢
        • 2011-03-25
        • 2022-01-05
        • 1970-01-01
        • 2014-02-16
        • 1970-01-01
        • 1970-01-01
        • 2015-11-01
        • 2013-09-20
        相关资源
        最近更新 更多