开发者

how to sort an NSArray of float values?

I have an NSArray like this:

h开发者_运维技巧ow to sort NSarray float with value like this:122.00,45.00,21.01,5.90


@Ron's answer is perfect, but I want to add sorting by using an comparator block. 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;
}];


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


Here... use NSSortDescriptor

First Convert the float values into 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 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜