2014-06-18 23 views
1

我使用showAnnotations方法在显示我的标记MKMapView在iOS7中。有时它完美地工作,并显示所有注释,但有时它会给出EXEC_BAD_ACCESS错误。在地图视图区域获取执行不良访问错误DigChangeAnimated

这是我的代码。

NSArray *annotations = MapView.annotations; 
_mapNeedsPadding = YES; 
[MapView showAnnotations:annotations animated:YES]; 

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{ 
    if(_mapNeedsPadding){ 
     [mapView setVisibleMapRect:mapView.visibleMapRect edgePadding:UIEdgeInsetsMake(100, 20, 10, 10) animated:YES]; 
     _mapNeedsPadding = NO; 
    } 
} 
+1

您是否设置了正确的代表?你是否正确使用强大的参考? 'EXC_BAD_ACCESS'通常表示您正在尝试引用已释放的实例。 – brandonscript

+0

我正在使用一个强大的引用属性,我正确地连接了我的MkMapView对象与xib.Delegates设置正确,为什么它调用mapView regiondidchangeanimated delegate.I不知道什么是问题 – user3698108

+0

问题发生后,你做了一些其他在视图控制器之间导航? – brandonscript

回答

1

中的代码,你得到EXC_BAD_ACCESS因为调用setVisibleMapRect导致regionDidChangeAnimated被再次地图视图这将启动一个无限递归调用。

即使你使用的是布尔标志_mapNeedsPadding有可能防止该递归的问题是标志被设置为NOsetVisibleMapRect后已经被调用(它有已经称为regionDidChangeAnimated和标志从未设置为NO)。

因此,您的代码调用setVisibleMapRect这会导致regionDidChangeAnimated再次被调用,导致无限递归导致堆栈溢出导致EXC_BAD_ACCESS


“速战速决” 是设置_mapNeedsPadding之前调用setVisibleMapRect

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{ 
    if(_mapNeedsPadding){ 
     _mapNeedsPadding = NO; // <-- call BEFORE setVisibleMapRect 
     [mapView setVisibleMapRect:mapView.visibleMapRect edgePadding:UIEdgeInsetsMake(100, 20, 10, 10) animated:YES]; 
    } 
} 


不过,我并不推荐这种方法开始。

相反,你应该根据你要显示和主代码(而不是showAnnotations:animated:)调用setVisibleMapRect:edgePadding:animated:注释手动计算MKMapRect

而且,不实施或在regionDidChangeAnimated中做任何事情。

例子:

NSArray *annotations = MapView.annotations; 
//_mapNeedsPadding = YES; 
//[MapView showAnnotations:annotations animated:YES]; 

MKMapRect rectForAnns = MKMapRectNull; 
for (id<MKAnnotation> ann in annotations) 
{ 
    MKMapPoint annPoint = MKMapPointForCoordinate(ann.coordinate); 

    MKMapRect annRect = MKMapRectMake(annPoint.x, annPoint.y, 1, 1); 

    if (MKMapRectIsNull(rectForAnns)) 
     rectForAnns = annRect; 
    else 
     rectForAnns = MKMapRectUnion(rectForAnns, annRect); 
} 

UIEdgeInsets rectInsets = UIEdgeInsetsMake(100, 20, 10, 10); 

[MapView setVisibleMapRect:rectForAnns edgePadding:rectInsets animated:YES]; 


//Do NOT implement regionDidChangeAnimated... 
//- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{ 
// if(_mapNeedsPadding){ 
//  [mapView setVisibleMapRect:mapView.visibleMapRect edgePadding:UIEdgeInsetsMake(100, 20, 10, 10) animated:YES]; 
//  _mapNeedsPadding = NO; 
// } 
//}