开发者

Sorting an NSArray of NSString

开发者 https://www.devze.com 2023-02-01 22:27 出处:网络
Can someone please show me the code for sorting an NSMutableArray? I have the following NSMutableArray:

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

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

with elements such as "2", "4", "5", "1", "9", etc which are all NSString.

I'd like to sort the list in 开发者_如何学JAVAdescending order so that the largest valued integer is highest in the list (index 0).

I tried the following:

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

but it did not seem to sort my values properly.

Can someone show me code for properly doing what I am trying to accomplish? Thanks!


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


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


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...


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


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

精彩评论

暂无评论...
验证码 换一张
取 消