1

I have an array of objects. On this object is a NSDecimalNumber property distanceFromDevice.

I want to order this array by this property. I have struggled for hours with sorting, anyone got any advice?

- (void)buildSearchableListUsing:(CLLocation *)newLocation
{
    listContent = [[NSMutableArray alloc] init];

    for(NSAirport *regionalAirport in airportsList)
    {
        CLLocation *location = [[CLLocation alloc]initWithLatitude:[regionalAirport.latitude doubleValue] longitude:[regionalAirport.longitude doubleValue]];

        regionalAirport.distanceFromDevice = [[NSDecimalNumber alloc]initWithDouble:[newLocation distanceFromLocation:location]];

        NSLog(@"distanceFromDevice %@", regionalAirport.distanceFromDevice);

        [listContent addObject:regionalAirport];
    }   

    //I want listContent ordered by the property distanceFromDevice
}
TheLearner
  • 18,967
  • 35
  • 92
  • 162

2 Answers2

1

Try this:

listContent = [[NSMutableArray alloc] init];
NSMutableArray *sortArray = [NSMutableArray array];
    for(NSAirport *regionalAirport in airportsList)
    {
        CLLocation *location = [[CLLocation alloc]initWithLatitude:[regionalAirport.latitude doubleValue] longitude:[regionalAirport.longitude doubleValue]];

        regionalAirport.distanceFromDevice = [[NSDecimalNumber alloc]initWithDouble:[newLocation distanceFromLocation:location]];

        NSLog(@"distanceFromDevice %@", regionalAirport.distanceFromDevice);

        //[listContent addObject:regionalAirport];
        [sortArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:regionalAirport,@"arrayElement",regionalAirport.distanceFromDevice,@"elementSorter",nil];

    }


    [sortArray sortUsingDescriptors:[NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"elementSorter" ascending:NO] autorelease]]];
    for(NSDictionary *dictionary in sortArray)
    {
        [listContent addObject:[dictionary valueForKey:@"arrayElement"]];
    }
ahmet emrah
  • 1,888
  • 2
  • 15
  • 22
-1

U can sort an NSArray in ascending manner in this way...

NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:nil
ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [myArrray sortedArrayUsingDescriptors:sortDescriptors];
NSLog(@"sortedArray%@",sortedArray);
Pradeep Reddy Kypa
  • 3,736
  • 7
  • 49
  • 73