5

我有一个 NSMutableArray,它保存了用户的高分。我想按数字排列项目(数字存储在 NSStrings 中。)
示例:
4,2,7,8

2,4,7,8
如果数据存储在 NSStrings 中,最简单的方法是什么?

4

5 回答 5

20

此代码将执行此操作:

//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);

它使用块,确保您的目标操作系统支持(iOS 为 4.0,OSX 为 10.6)。

于 2012-06-24T21:57:47.157 回答
1

此代码有效。我尝试过这个:

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

输出是这样的:

2

4

7

8

如果您对代码有任何疑问,请在评论中提问。希望这可以帮助!

于 2012-06-24T21:34:06.763 回答
1

NSMutableArray 方法sortUsingSelector:应该这样做:

[scoreArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)]

应该这样做。

于 2012-06-24T21:39:57.853 回答
1

如果数组是包含键的数值的 nsdictionariesnumber

isKeyAscending = isKeyAscending ? NO : YES;

[yourArray sortUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {

    NSString *str1 = [obj1 objectForKey:@"number"];
    NSString *str2 = [obj2 objectForKey:@"number"];

    if(isKeyAscending) { //ascending order
        return [str1 compare:str2 options:(NSNumericSearch)];
    } else { //descending order
        return [str2 compare:str1 options:(NSNumericSearch)];
    }
}];

//yourArray is now sorted
于 2015-04-12T10:37:57.633 回答
0

Darshit Shah回答让事情变得顺利

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc]initWithKey:@"rank"  ascending:YES selector:@selector(localizedStandardCompare:)];
于 2021-06-02T23:18:11.587 回答