所以我有一个带有纬度和经度值的点数据集,我想检索它们并按照到用户当前位置的距离对它们进行排序。目前,我有以下内容:
mainMoc.performBlockAndWait {
// Fetching data from CoreData
let fetchRequest = NSFetchRequest()
fetchRequest.predicate = NSPredicate(format: "pointLatitude BETWEEN {%f,%f} AND pointLongitude BETWEEN {%f,%f}", (latitude-0.03), (latitude+0.03), (longitude-0.03), (longitude+0.03))
let entity = NSEntityDescription.entityForName("PointPrimary", inManagedObjectContext: self.mainMoc)
fetchRequest.entity = entity
let sortDescriptor = NSSortDescriptor(key: "pointTitle", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor]
do {
points = try self.mainMoc.executeFetchRequest(fetchRequest) as! [PointPrimary]
} catch {
let jsonError = error as NSError
NSLog("\(jsonError), \(jsonError.localizedDescription)")
abort()
}
}
所以目前我只根据标题对其进行排序。但是,如果我想计算一个CLLocationCoordinate2D的距离并根据它来对fetchRequest结果进行排序,我将如何继续?
非常感谢!
答案 0 :(得分:0)
这应该有效。基本上,您将NSSortDescriptor
与自定义比较器一起使用。
诀窍是使用"self"
作为NSSortDescriptor
的键,它将获取的对象传递给比较器。
var userLocation : CLLocation // get that from somewhere
var distanceCompare : NSComparator = {
(obj1: AnyObject!, obj2: AnyObject!) -> NSComparisonResult in
let lng1 = obj1.valueForKey("pointLongitude") as! CLLocationDegrees
let lat1 = obj1.valueForKey("pointLatitude") as! CLLocationDegrees
let p1Location : CLLocation = CLLocation(latitude: lat1, longitude: lng1)
let p1DistanceToUserLocation = userLocation.distanceFromLocation(p1Location)
let lng2 = obj2.valueForKey("pointLongitude") as! CLLocationDegrees
let lat2 = obj2.valueForKey("pointLatitude") as! CLLocationDegrees
let p2Location : CLLocation = CLLocation(latitude: lat1, longitude: lng1)
let p2DistanceToUserLocation = userLocation.distanceFromLocation(p2Location)
if (p1DistanceToUserLocation > p2DistanceToUserLocation) {
return .OrderedDescending
} else if (p1DistanceToUserLocation < p2DistanceToUserLocation) {
return .OrderedAscending
} else {
return .OrderedSame
}
}
var distanceSortDescriptor = NSSortDescriptor(key: "self", ascending: true, comparator: distanceCompare)
fetchRequest.sortDescriptors = [distanceSortDescriptor]
答案 1 :(得分:0)
NSFetchRequest
不能使用模型中定义的属性(并存储在数据库中)作为排序描述符,因此您不得不求助于内存中排序。在distance
类上定义执行适当计算的PointPrimary
方法并执行:
let sortedPoints = points.sortedArrayUsingDescriptors([NSSortDescriptor(key: "distance", ascending: true)])