I have records in my Core Data store with latitude and longitude properties. Now I need to find the record that is closest to a given location. In SQL I would do it like:
select t.lat
,t.lon
,(t.lat-varLat) + (t.lon - varLon) diff
from table t
order by diff ASC.
given varLat and varLon are the coordinates of the location I want the closest record to. However I have no clue how to do this in Core Data with an NSPredicate.
The worst thing I can imagine is looping fetchrequests with a predicate that expands a 'search range' around the given (varLat,varLon), and using
longitude BETWEEN %@ && latitude BETWEEN %@ with 2 arrays (each having center+ and center- radius as array members) as parameters, each time expanding this range until I get a hit.. however, this is far from optimal.
Thanks for your advice.