我有一个NSMutableArray,它保存了高分的用户。我想用数字排列项目(数字存储在NSStrings中。)例如:
4,2,7,8
到
2,4,7,8 <如果数据存储在NSStrings中,最简单的方法是什么?
答案 0 :(得分:19)
此代码将执行此操作:
//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)。
答案 1 :(得分: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
如果您对代码有任何疑问,请在评论中提问。希望这有帮助!
答案 2 :(得分:1)
NSMutableArray方法sortUsingSelector:应该这样做:
[scoreArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)]
应该这样做。
答案 3 :(得分:1)
如果数组是包含键number
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
答案 4 :(得分:0)
The answer 来自 Darshit Shah 使它顺利
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc]initWithKey:@"rank" ascending:YES selector:@selector(localizedStandardCompare:)];