3

I have an NSArray like this:

how to sort NSarray float with value like this:122.00,45.00,21.01,5.90

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
Chirag S
  • 364
  • 3
  • 12

3 Answers3

11

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:)];
vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
Rahul Juyal
  • 2,124
  • 1
  • 16
  • 33
11

@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;
}];
Community
  • 1
  • 1
vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
0

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

Shrey
  • 1,959
  • 2
  • 21
  • 44