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 descending 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!
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
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
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]];
}];
来源:https://stackoverflow.com/questions/4558761/sorting-an-nsarray-of-nsstring