Question

I've an array from core data and I'm trying to think how can I sort the array by the nearest distance:

for (int i=0; i<allTasks.count; i++) {
        id singleTask = allTasks[i];
        double latitude = [singleTask[@"latitude"] doubleValue];
        double longitude = [singleTask[@"longitude"] doubleValue];
    }

EDIT: The distance between current location and all the locations in the array. I know how to calculate the distance, I don't know how to sort them.

Was it helpful?

Solution 2

  1. get the CLLocation for your currentPosition (this is done via CLLocationManager)

  2. calculate the distances for each item and store distance+item as a Pair in a Dictionary

  3. Sort Dictionary allKeys array with compare: selector

so

CLLocation *current = ...;
NSMutableDictionary *distsAndTasks [NSMutableDictionary dictionary];

for(id task in allTasks) {
    CLLocation *taskLoc = [[CLLocation alloc] initWithLatitude:task.lat longitude:task.long];//!
    CLLocationDistance dist = [taskLoc distanceFrom:current];
    if(distsAndTasks[@(dist)]) {
        NSMutableArray *equidstants = [distsAndTasks[@(dist)] mutableCopy];
        [equidstants addObject:task]; 
        distsAndTasks[@(dist)] = equidstants; 
    }
    else {
        distsAndTasks[@(dist)] = @[task]; 
    }
}

NSArray *sortedDists = [distsAndTasks.allKeys sortedArrayUsingSelector:@selector(compare:)];

//the tasks can now be access in a sorted way
for(NSNumber *dist in sortedDists) {
    NSArray *tasksAtDistance = distsAndTasks[dist];
    NSLog(@"%@", tasksAtDistance);
}

OTHER TIPS

So do you want to sort your allTasks array?

The best thing to do would be to add a distance key/value pair to each singleTask object, holding a double NSNumber.

In a first pass, loop through your allTasks array, fetch each lat/long, use it to create a CLLocation, and use the CLLocation method distanceFromLocation: to calculate the distance between each location and your target (current?) location. Save the result into each singleTask object in your array.

Once your allTasks array contains a distance property, simply use one of the sort methods like sortUsingComparator to sort the array based on the distance value. (In the sortUsingComparator family of methods, you provide a comparator block that the system uses to compare pairs of objets. It then runs a sort algorithm on your array, using your comparator to decide on the sort order.

You can calculate distance between two points like this

You can also try this https://stackoverflow.com/a/9104926/3151066 and define some way of calculating distance that will satisfy you as the comparison operator

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top