NSSortDescriptor must be initialized with a key string for an object property, not a query string. This means that you must use the distance formula as a method of your object.
After that, it doesnβt matter if you sort before or after fetching:
NSArray *result = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error]; result = [result sortedArrayUsingSelector:@"compareDistance"];
Another point. Your distance formula does not work correctly, like lat. and for a long time. do not have the same scale if you are not at the equator. Use this:
double latDiff = lat1-lat2; double longDiff = (long1-long2)*cos(lat1);
If the distance is more than a few hundred kilometers, you need the Law on Spherical Cosines :
// assuming angles in radian, double separation = acos( sin(lat1)*sin(lat2) + cos(lat1)*cos(lat2)*cos(long1-long2) ); double distance = separation*earthRadius;
source share