Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array of NSDictionaries by a value inside one of the keys [duplicate]

I'm pulling an XML feed from a server, the feed contains train stations and their latitude and longitude locations.

I've managed to create an NSArray full of NSDictionary objects, each corresponding to a station.

In the dictionary there is a key for latitude and key for longitude. I also have a CLLocation object with the location of the device.

I know how to calculate the distance between the device and each station, but the distance isn't part of the dictionary. I would like to sort the array in order of distance from the device.

How would I do that? No idea where to start on this and Google or my books aren't being very helpful to me! Any help is much appreciated.

like image 959
Adam Waite Avatar asked Dec 13 '22 04:12

Adam Waite


1 Answers

Use the following;

NSArray *sortedArray;
sortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *first, NSDictionary *second) {
    // Calculate distances for each dictionary from the device
    // ...
    return [firstDistance compare:secondDistance];
}];
like image 182
jrtc27 Avatar answered Dec 15 '22 00:12

jrtc27