我正在开发一个在 iOS 中使用 MapKit 的应用程序。我遇到了麻烦,因为在我的程序中的某个时刻,其中一个数组的顺序切换(保存坐标的数组),导致地名与错误的坐标配对。我已将其缩小到以下区域:
for(CLLocation *loc in locationOutputArray)
{
NSLog(@"Location coordinates: %f,%f",[loc coordinate].latitude,
[loc coordinate].longitude);
}
NSLog(@"***************************************");
for(CLLocation *location in locationOutputArray)
{
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:location
completionHandler:^(NSArray *placemarks, NSError *error)
{
NSLog(@"Location coordinates:%f,%f",[location coordinate].latitude,
[location coordinate].longitude);
if(placemarks && placemarks.count > 0)
{
CLPlacemark *topResult = [placemarks objectAtIndex:0];
//NSLog(@"%@",topResult);
NSString *address = [NSString stringWithFormat:@"%@ %@, %@ %@",
[topResult subThoroughfare],
[topResult thoroughfare],
[topResult locality],
[topResult administrativeArea]];
//NSLog(@"Address: %@", address);
[addressOutputArray addObject:address];
Place *place = [[Place alloc]
initWithName:[namesOutputArray objectAtIndex:([addressOutputArray count]-1)]
andAddress:address
andLatitude:[location coordinate].latitude
andLongitude:[location coordinate].longitude
andStartingCoordinate:startingCoordinate];
//NSLog(@"Distance from starting location: %f",[place distanceFromStartingPoint]);
[finalPlaceArray addObject:place];
[place release];
}`
代码块前后的日志语句(以星号分隔)分别为:
位置坐标:40.116903,-75.120631
位置坐标:40.129940,-75.060127
位置坐标:40.083996,-75.187704
位置坐标:40.069180,-75.126812
位置坐标:40.095425,-75.127777
位置坐标:40.095019,-75.126752
位置坐标:40.117596,-75.185366
位置坐标:40.105838,-75.212272
位置坐标:40.124327,-75.061865
位置坐标:40.010910,-75.127223
位置坐标:40.061088,-75.092801
位置坐标:40.112011,-75.165353
位置坐标:40.017103,-75.174498
位置坐标:40.139532,-75.207757
位置坐标:40.099432,-75.196213
位置坐标:40.116903,-75.120631
位置坐标:40.061088,-75.092801
位置坐标:40.010910,-75.127223
位置坐标:40.124327,-75.061865
位置坐标:40.112011,-75.165353
位置坐标:40.099432,-75.196213
位置坐标:40.139532,-75.207757
位置坐标:40.017103,-75.174498
位置坐标:40.083996,-75.187704
位置坐标:40.069180,-75.126812
位置坐标:40.129940,-75.060127
位置坐标:40.095019,-75.126752
位置坐标:40.117596,-75.185366
位置坐标:40.095425,-75.127777
位置坐标:40.105838,-75.212272
如有任何帮助,我们将不胜感激。
最佳答案
简短回答:您正在按照地理编码器请求完成的顺序打印位置,而不是它们在数组中出现的顺序。
较长的答案:您正在对地理编码器进行一系列调用(对数组中的每个位置进行一次调用),并传入一个完成处理程序。这些调用是异步的,这意味着您不会在启动下一个调用之前等待一个调用完成。每次调用完成后,您打印它的位置。因此,您获得的输出代表调用完成的顺序,而不是位置在原始数组中出现的顺序或您进行调用的顺序。
解决方案:不要依赖异步调用以任何特定顺序完成。如果您需要结果以某种顺序出现,您将需要一种方法来对它们进行排序。听起来您将地名和位置保存在单独的数组中,并试图使这些数组的顺序相同。这总是错误的秘诀;您最好将所有内容都保存在一个数组中,数组中的每个条目都包含地名和位置。为每个地方使用字典可能是实现这一目标的便捷方式。
关于iphone - 更改数组中对象的顺序而不调用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6767554/