Sort by distance

I have a set of dictionaries in an array. I show this data in a table. In the table view, I calculate the distance to each object and display it in a cell.

Data should be able to sort based on the upstream distance, obviously for each user. What is the best way to approach this? I was thinking about separating all the dictionaries and inserting the distance and then freeing the NSSortDescriptor, the problem is that I'm too lazy for that.

Right now, I'm just looking at all the data using indexPath.row and displaying it.

+5
source share
1 answer

You can easily sort using a comparator based on api block.

NSArray *rawData = [NSArray arrayWithContentsOfFile:pathDoc];

rawData = [rawData sortedArrayUsingComparator: ^(id a, id b) {

    CLLocationDistance dist_a= [[a objectsForKey:@"coordinate"] distanceFromLocation: userPosition];
    CLLocationDistance dist_b= [[b objectsForKey:@"coordinate"] distanceFromLocation: userPosition];
    if ( dist_a < dist_b ) {
        return NSOrderedAscending;
    } else if ( dist_a > dist_b) {
        return NSOrderedDescending;
    } else {
        return NSOrderedSame;
    }
}];

calculate_distance(user_position, a); google.

+13

All Articles