Sorting an NSArray of NSString

前端 未结 5 1656
名媛妹妹
名媛妹妹 2020-12-16 12:36

Can someone please show me the code for sorting an NSMutableArray? I have the following NSMutableArray:

NSMutableArray *arr = [[NSMutableArray alloc] init];
         


        
相关标签:
5条回答
  • 2020-12-16 12:39

    If the array's elements are just NSStrings with digits and no letters (i.e. "8", "25", "3", etc.), here's a clean and short way that actually works:

    NSArray *sortedArray = [unorderedArray sortedArrayUsingComparator:^(id a, id b) {
        return [a compare:b options:NSNumericSearch];
    }];
    

    Done! No need to write a whole method that returns NSComparisonResult, or eight lines of NSSortDescriptor...

    0 讨论(0)
  • 2020-12-16 12:50

    You should use this method:

    [arr sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
    

    in a NSArray or:

    [arr sortUsingSelector:@selector(caseInsensitiveCompare:)];
    

    in a "inplace" sorting NSMutableArray

    The comparator should return one of this values:

    • NSOrderedAscending
    • NSOrderedDescending
    • NSOrderedSame
    0 讨论(0)
  • 2020-12-16 12:50

    IMHO, easiest way to sort such array is

    [arr sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self.intValue" ascending:YES]]]
    

    If your array contains float values, just change key to self.floatValue or self.doubleValue

    0 讨论(0)
  • 2020-12-16 12:58

    It's pretty simple to write your own comparison method for strings:

    @implementation NSString(compare)
    
    -(NSComparisonResult)compareNumberStrings:(NSString *)str {
        NSNumber * me = [NSNumber numberWithInt:[self intValue]];
        NSNumber * you = [NSNumber numberWithInt:[str intValue]];
    
        return [you compare:me];
    }
    
    @end
    
    0 讨论(0)
  • 2020-12-16 13:03

    The easiest way would be to make a comparator method like this one

    NSArray *sortedStrings = [stringsArray sortedArrayUsingComparator:^NSComparisonResult(NSString *firstString, NSString *secondString) {
        return [[firstString lowercaseString] compare:[secondString lowercaseString]];
    }];
    
    0 讨论(0)
提交回复
热议问题