2016-01-27 28 views
0

因此,我有一个包含纬度和经度值的点的数据集,我想检索它们并按照距离用户当前位置进行排序。目前,我有以下内容:按计算结果对NSFetchRequest进行排序

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

这应该起作用。基本上你会使用自定义比较器的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] 
0

NSFetchRequest不能使用比在模型中定义(并存储在数据库中)的排序描述符等特性,所以你必须诉诸于内存中的排序。在您的PointPrimary类中定义一个distance方法,该类执行相应的计算,并执行以下操作:

let sortedPoints = points.sortedArrayUsingDescriptors([NSSortDescriptor(key: "distance", ascending: true)])