我得到以下函数以获得最接近用户位置的对象。有没有其他方法?我想让我的代码更清晰。是否可以使用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;
}
看起来相当清楚,并且几乎是唯一的方法,如果你是你的对象安排在一维数组。 – trojanfoe
您可以将返回的类型更改为“ELBaseAgglomeration”,因为这是您实际返回的内容。 – tilo