objective-C,对包含数字的字符串数组进行排序 [英] objective-C, sort an array of strings containing numbers
本文介绍了objective-C,对包含数字的字符串数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个像这样的数组
Lets suppose I have an array like this
NSArray* arr = @[@"1",@"4",@"2",@"8",@"11",@"10",@"14",@"9"]; //note: strings containing numbers
我希望对它们进行排序:[1,2, 4,8,9,10,11,14]
and I want to sort them like this: [1,2,4,8,9,10,11,14]
但如果我使用
[arr sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
我得到[1,10,11,14,2,4,8,9] ..如果我使用:
I get [1,10,11,14,2,4,8,9]... and if I use:
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"length" ascending:YES];
NSArray *sortDescriptors = @[sortDescriptor];
[arr sortedArrayUsingDescriptors:sortDescriptors];
我得到这样的东西:[1,4,2,8,9,11,10, 14]
I get something like this: [1,4,2,8,9,11,10,14]
如何组合两个谓词?或者是解决这个问题的其他更简单的方法吗?注意:这个数组的输出仅用于调试目的,我不在乎结果是否将数组转换为整数,只要我可以在控制台中使用NSLog打印谢谢
How can I combine both predicates? or is any other easier way to solve this? note: The output of this array is merely for debug purposes, I dont care if the result turns the array into integers as long as I can print in console with NSLog thanks
推荐答案
尝试使用块
[arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if ([obj1 intValue] == [obj2 intValue])
return NSOrderedSame;
else if ([obj1 intValue] < [obj2 intValue])
return NSOrderedAscending;
else
return NSOrderedDescending;
}];
这篇关于objective-C,对包含数字的字符串数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文