问题
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.
回答1:
get the CLLocation for your currentPosition (this is done via CLLocationManager)
calculate the distances for each item and store distance+item as a Pair in a Dictionary
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);
}
回答2:
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.
回答3:
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
来源:https://stackoverflow.com/questions/20921468/how-to-sort-array-of-objectslatitude-longitude-by-nearest-distance