Sort NSMutableArray with strings that contain numbers?

后端 未结 4 1513
北恋
北恋 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条回答
  •  醉梦人生
    2021-01-06 02:14

    This code works. I tried it:

    NSMutableArray *unsortedHighScores = [[NSMutableArray alloc] initWithObjects:@"4", @"2", @"7", @"8", nil];
    
    NSMutableArray *intermediaryArray = [[NSMutableArray alloc] init];
    
    for(NSString *score in unsortedHighScores){
        
        NSNumber *scoreInt = [NSNumber numberWithInteger:[score integerValue]];
        [intermediaryArray addObject:scoreInt];
    }
    
    NSArray *sortedHighScores = [intermediaryArray sortedArrayUsingSelector:@selector(compare:)];
    NSLog(@"%@", sortedHighScores);
    

    The output is this:

    2

    4

    7

    8

    If you have any questions about the code, just ask in the comments. Hope this helps!

提交回复
热议问题