简体   繁体   English

如何对浮动值的NSArray进行排序?

[英]how to sort an NSArray of float values?

I have an NSArray like this: 我有一个像这样的NSArray:

how to sort NSarray float with value like this:122.00,45.00,21.01,5.90 如何使用这样的值对NSarray float进行排序:122.00,45.00,21.01,5.90

try this it work for me 试试这个对我有用

NSArray *array=[[NSArray alloc] initWithObjects:[NSNumber numberWithFloat:12.01],[NSNumber numberWithFloat:13.01],[NSNumber numberWithFloat:10.01],[NSNumber numberWithFloat:2.01],[NSNumber numberWithFloat:1.5],nil];
NSArray *sorted = [array sortedArrayUsingSelector:@selector(compare:)];

@Ron's answer is perfect, but I want to add sorting by using an comparator block. @ Ron的答案很完美,但我想通过使用比较器块来添加排序。 For this trivial case it might be overkill, but it is very handy when it comes to sorting of objects in respect to several properties 对于这个微不足道的情况,它可能是矫枉过正的,但在涉及对几个属性的对象排序时非常方便

NSArray *myArray =[NSArray arrayWithObjects: [NSNumber numberWithFloat:45.0],[NSNumber numberWithFloat:122.0], [NSNumber numberWithFloat:21.01], [NSNumber numberWithFloat:5.9], nil];
NSArray *sortedArray = [myArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    if ([obj1 floatValue] > [obj2 floatValue])
        return NSOrderedDescending;
    else if ([obj1 floatValue] < [obj2 floatValue])
        return NSOrderedAscending;
    return NSOrderedSame;
}];

Here... use NSSortDescriptor 这里......使用NSSortDescriptor

First Convert the float values into NSNumber 首先将浮点值转换为NSNumber

NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"floatValue"
                                              ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingDescriptors:sortDescriptors];

Hope it helps :) 希望能帮助到你 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM