4

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.

Pramod More
  • 1,220
  • 2
  • 22
  • 51
Adam Waite
  • 19,175
  • 22
  • 126
  • 148
  • 2
    This post has the answer to your question: [http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it][1] [1]: http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it – Boon Feb 27 '12 at 22:03
  • If anyone else is having a problem like this - make the array mutable, create a method using fast enumeration to add another field to each dictionary. Do the sort using blocks (as described in the link above) – Adam Waite Feb 29 '12 at 13:19

2 Answers2

10

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];
}];
jrtc27
  • 8,496
  • 3
  • 36
  • 68
3

Unfortunately, you can't sort NSDictionary objects. You should create NSMutableArray and sort it instead.

See this - Collections Programming Topics - Sorting Arrays

Update: To sort array of dictionaries you can use for example this method of NSArray:

sortedArray = [someArray sortedArrayUsingFunction:compareElements context:NULL];

The compareElements function example:

NSInteger compareElements (id num1, id num2, void *context)
{
    int v1 = [[num1 objectForKey:@"distance"] integerValue];
    int v2 = [[num2 objectForKey:@"distance"] integerValue];
    if (v1 < v2)
        return NSOrderedAscending;
    else if (v1 > v2)
        return NSOrderedDescending;
    else
        return NSOrderedSame;
}
Nilanshu Jaiswal
  • 1,583
  • 3
  • 23
  • 34
SVGreg
  • 2,320
  • 1
  • 13
  • 17