Sort NSMutableArray with strings that contain numbers?

后端 未结 4 1548
北恋
北恋 2021-01-06 02:01

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

4条回答
  •  旧时难觅i
    2021-01-06 02:25

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

提交回复
热议问题