Last Updated: September 09, 2019
·
3.635K
· jfsagasti

How to sort a NSArray of NSDictionaries by distance

Suppose you have a TableView filled with the info of a NSArray (self.shopsArray). Each position in the array has a NSDictionary with the info of a shop (retrieved from a REST API, Plist file, whatever):

{
        id = 1;
        latitude = "-25.0007";
        longitude = "-23.5678";
        name = "An awesome shop";
}

Then you can sort it in a nice way using a Comparator:

- (void)sortTableWithCurrentLocation:(CLLocation *)currentLocation
{
    self.shopsArray = [self.shopsArray sortedArrayUsingComparator: ^(id a, id b)
    {
        CLLocation *shopLocationA = [[CLLocation alloc] initWithLatitude:[[a objectForKey:@"latitude"] doubleValue] longitude:[[a objectForKey:@"longitude"] doubleValue]];
        CLLocation *shopLocationB = [[CLLocation alloc] initWithLatitude:[[b objectForKey:@"latitude"] doubleValue] longitude:[[b objectForKey:@"longitude"] doubleValue]];

        CLLocationDistance distA = [shopLocationA distanceFromLocation:currentLocation];
        CLLocationDistance distB = [shopLocationB distanceFromLocation:currentLocation];

        if (distA < distB) {
            return (NSComparisonResult)NSOrderedAscending;
        } else if ( distA > distB) {
            return (NSComparisonResult)NSOrderedDescending;
        } else {
            return (NSComparisonResult)NSOrderedSame;
        }
    }];

    [self.tableView reloadData];
}

1 Response
Add your response

Thanks, I learnt that there is class CLLocation to handle location stuff.

over 1 year ago ·