Can someone please show me the code for sorting an NSMutableArray? I have the following NSMutableArray:
NSMutableArray *arr = [[NSMutableArray alloc] init];
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
...
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
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
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
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]];
}];