2014-01-27 47 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) –