wuvt_g
Last Updated: February 25, 2016
·
2.506K
· jfsagasti
U1b6bd8ad071161fb5bd43535867f4590

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];
}
Say Thanks
Respond

1 Response
Add your response

13830
2a92ad89c8bd4e8b45edc8f363e18aa3 normal

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

over 1 year ago ·