2014-01-27 50 views
0

我得到以下函数以获得最接近用户位置的对象。有没有其他方法?我想让我的代码更清晰。是否可以使用NSPredicate解决此问题?对象MyZone包含CLLocationCoordinate2D获得最接近元素的最佳方法

- (MyZone *)closestBaseAgglomeration { 
    CLLocation *userLocation = self.locationManager.location; 
    NSArray *zoneArr = //Get zone array here 
    CLLocationDistance minDist = CGFLOAT_MAX; 
    MyZone *closestZone = nil; 
    for (int it=0; it<zoneArr.count; it++) { 
     MyZone *curZone = [zoneArr objectAtIndex:it]; 
     CLLocationCoordinate2D curCoordinate = curZone.coordinateRegion.center; 
     CLLocation *curLocation = [[CLLocation alloc] initWithLatitude:curCoordinate.latitude longitude:curCoordinate.longitude]; 
     CLLocationDistance actDist = [curLocation distanceFromLocation:userLocation]; 
     if (minDist > actDist) { 
      closestZone = curZone; 
      minDist = actDist; 
     } 
    } 
    return closestZone; 
} 
+0

看起来相当清楚,并且几乎是唯一的方法,如果你是你的对象安排在一维数组。 – trojanfoe

+0

您可以将返回的类型更改为“ELBaseAgglomeration”,因为这是您实际返回的内容。 – tilo

回答

1

您可以使用对indexOfObjectPassingTest方法的调用并传入一个块,以选择距离距离当前位置最近的对象。我不知道你是否会考虑更清楚与否。

如果您正在重复执行此操作或在大量位置上执行此操作,那么为每个位置创建CLLocation对象的开销将变得很大。您可能需要将CLLocation属性添加到MyZone类中,并将对象的位置保存在CLLocation中而不是使用经纬度值。这样,您可以避免每次想要查找最近的对象时为数组中的每个条目创建CLLocation对象。 CLLocation符合NSCoding,所以你可以很容易地将它保存到一个失败...

2

为了使其更具可读性一点,你可以改变你的for循环像

for (MyZone *curZone in zoneArr.count) { 
.. 
} 

也许CLLocationCoordinate2D和CLLocation之间的距离计算和转换进入你的MyZone类的新方法。

+0

同意。对...而言,语法是一种改进。 (1) –