xcode 使用包含数字的字符串对数组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13353150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting an Array with Strings that contains Numbers
提问by user1639377
Possible Duplicate:
Sorting NSString values as if NSInteger using NSSortDescriptor
I have an Array that I fill with my NSMutableDictionary.. and I use this:
我有一个用我的 NSMutableDictionary 填充的数组..我使用这个:
myArray =[[myDict allKeys]sortedArrayUsingSelector:@selector(IDONTKNOW:)];
AllKeys of myDicts are NSStrings... like 123.423 or 423.343... I need to sort the new myArray by incremental numbers.. 12.234 45.3343 522.533 5432.66 etc etc
myDicts 的 AllKeys 是 NSStrings... 像 123.423 或 423.343... 我需要按递增数字对新的 myArray 进行排序... 12.234 45.3343 522.533 5432.66 等等
What must insert in @selector to do this properly? Thanks
必须在@selector 中插入什么才能正确执行此操作?谢谢
回答by Joe
You can use an NSSortDescriptor
and pass doubleValue
as the key.
您可以使用 anNSSortDescriptor
和 passdoubleValue
作为密钥。
//sfloats would be your [myDict allKeys]
NSArray *sfloats = @[ @"192.5235", @"235.4362", @"3.235", @"500.235", @"219.72" ];
NSArray *myArray = [sfloats sortedArrayUsingDescriptors:
@[[NSSortDescriptor sortDescriptorWithKey:@"doubleValue"
ascending:YES]]];
NSLog(@"Sorted: %@", myArray);
回答by bbum
You can't direclty use sortedArrayUsingSelector:
. Use sortedArrayUsingComparator:
and implement a comparison block yourself.
你不能直接使用sortedArrayUsingSelector:
. sortedArrayUsingComparator:
自己使用和实现一个比较块。
Kinda like this q/a:
有点像这样 q/a:
Changing the sort order of -[NSArray sortedArrayUsingComparator:]
更改 -[NSArray sortedArrayUsingComparator:] 的排序顺序
(In fact, that Question's code can likely be copy/pasted into your code and it'll "just work" once you change it from integerValue
to doubleValue
for the four convert-string-to-number calls):
(事实上,这个问题的代码可能可以复制/粘贴到你的代码,它会“只是工作”,一旦你改变它integerValue
到doubleValue
四个转换字符串到数字电话):
NSArray *sortedArray = [array sortedArrayUsingComparator: ^(id obj1, id obj2) {
double n1 = [obj1 doubleValue];
double n2 = [obj2 doubleValue];
if (n1 > n2) {
return (NSComparisonResult)NSOrderedDescending;
}
if (n1 < n2) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
回答by jimbo
Consider sortedArrayUsingFunction:
. This allows you to define a custom comparison function to employ when comparing elements.
考虑sortedArrayUsingFunction:
。这允许您定义在比较元素时使用的自定义比较函数。
myArray =[[myDict allKeys]sortedArrayUsingFunction:SortAsNumbers context:self];
NSInteger SortAsNumbers(id id1, id id2, void *context)
{
float v1 = [id1 floatValue];
float v2 = [id2 floatValue];
if (v1 < v2) {
return NSOrderedAscending;
} else if (v1 > v2) {
return NSOrderedDescending;
}
return NSOrderedSame;
}
More info available here: Sort NSArray using sortedArrayUsingFunction