代码之家  ›  专栏  ›  技术社区  ›  Girish Kolari

按降序排列数组(nsarray)

  •  21
  • Girish Kolari  · 技术社区  · 15 年前

    我有一个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:)];
    

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

    3 回复  |  直到 7 年前
        1
  •  54
  •   dgatwood    7 年前

    可以使用nsSortDescriptor:

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

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

        2
  •  4
  •   ankit yadav    12 年前
    NSSortDescriptor *sortDescriptor; 
    sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"length" ascending:NO];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    [wordsArray sortUsingDescriptors:sortDescriptors];
    

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

        3
  •  4
  •   Jiri Zachar    10 年前

    或者简化您的解决方案:

    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);
    
    推荐文章