Sirens Sirens - 4 months ago 30
Objective-C Question

Sort NSMutableArray with strings that contain numbers?

I have a NSMutableArray and it has the users high scores saved into it. I want to arrange the items numerically (the numbers are stored in NSStrings.)
Example:
4,2,7,8
To
2,4,7,8
What is the simplest way to do this if the data is stored in NSStrings?

Answer

This code will do it:

//creating mutable array
NSMutableArray *myArray = [NSMutableArray arrayWithObjects:@"4", @"2", @"7", @"8", nil];

//sorting
[myArray sortUsingComparator:^NSComparisonResult(NSString *str1, NSString *str2) {
    return [str1 compare:str2 options:(NSNumericSearch)];
}];

//logging
NSLog(@"%@", myArray);

It uses blocks, make sure your target OS supports that (It's 4.0 for iOS and 10.6 for OSX).