Sirens Sirens - 1 year ago 77
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.)
What is the simplest way to do this if the data is stored in NSStrings?

Answer Source

This code will do it:

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

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

NSLog(@"%@", myArray);

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