2015-04-21 46 views
2

我从核心数据实体填充了UITableView以显示位置名称以及这些位置的纬度和经度。在Swift中按距离对UItableview进行排序

我设法计算从用户到存储位置的距离并显示距离。

 var templat = NSString(string: location.lat) 
     var templong = NSString(string: location.long) 
     var distinationCoords: CLLocation = CLLocation(latitude: templat.doubleValue, longitude: templong.doubleValue) 
     var distance: CLLocationDistance = distinationCoords.distanceFromLocation(mypoi.sharedlocation) 
     classdistance = distance/1000 

     cell.customCellSubTitle?.text = "\(distance)" 

现在,我该如何根据距离当前位置的距离排序位置。

我可以很容易地按名称排序或存储在核心数据的任何值,但距离需要从检索到的数据计算,当我做计算这将是

请帮助,如果后期这样排序细胞你可以

非常感谢你提前

+1

的延伸?如果是,则存储与coredata的距离并使用NSSortDescriptor对它们进行排序。如果您想要更多帮助,请告诉我 –

+0

您无法在NSSortDescriptor中计算距离,因为您必须使用CLLocation&CLLocationDistance。 –

+0

你的核心数据实体有哪些属性? – ABakerSmith

回答

0

例如,你的tableview是通过DATAS与结构列表填充:

struct Position { 
    var latitude : Double 
    var longitude: Double 
    //you add a function to compare a position to another 
    func getDistance(CLLocation current) -> double { 
     //calculate the distance here 
    } 
} 

然后,用你的位置

var positions = ... the list of positions ... 
positions.sort({$0.getDistance(currentPos) > $1.getDistance(currentPos)}) 

这里的想法是利用数组的.sort功能在迅速排序列表的列表。您必须定义.getDistance()才能正确排序数组。

如果你有一个NSManagedObject来获取tableviewcell,你可以使用扩展来为你的NSManagedObject添加getDistance。 例如,你的类名为“富”(其中包含名称,纬度,经度,时间戳),您可以您是否使用NSFetchResultController添加像

extension Foo { 
    func getDistance(CLLocation current) { 
     //your calculation using Location API 
    } 
} 
+0

我的tableview使用coreData不是列表 设位置= fetchedResultsController.objectAtIndexPath(indexPath)作为myLocations –

+0

您可以使用斯威夫特扩展添加的功能getDistance的你NSmanagedObject。看到我更新的答案 –

相关问题