【问题标题】:Getting exec bad access error in mapView regionDidChangeAnimated在 mapView regionDidChangeAnimated 中获取 exec 错误访问错误
【发布时间】:2014-06-18 04:11:12
【问题描述】:

我正在使用 showAnnotations 方法在 iOS7 中的 MKMapView 上显示我的标记。有时它可以完美运行并显示所有注释,但有时它会给出 EXEC_BAD_ACCESS 错误。

这是我的代码。

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;
    }
}

【问题讨论】:

  • 您是否正确设置了代表?您是否正确使用了强参考? EXC_BAD_ACCESS 通常表示您正在尝试引用已释放的实例。
  • 我正在使用强引用属性,并且我将我的 MkMapView 对象与 xib 正确连接。代理设置正确,为什么它调用 mapView regiondidchangeanimated 代理。我不知道是什么问题
  • 在视图控制器之间进行了一些其他导航后是否会出现问题?
  • 是的,只有当我从一个视图控制器移动到另一个视图控制器时才会出现此问题。在导航期间,我正在将我的 mkmapview 加载到搜索站
  • 您是否尝试在多个实例中使用相同的实例?如果是这样,请尝试在导航控制器中设置委托方法。

标签: ios objective-c ios7


【解决方案1】:

在显示的代码中,您将获得EXC_BAD_ACCESS,因为调用setVisibleMapRect 会导致地图视图再次调用regionDidChangeAnimated,从而开始无限递归。

即使您使用布尔标志 _mapNeedsPadding 来防止这种递归,问题是标志被设置为 NO 之后 setVisibleMapRect 已经被调用(并且它已经调用了regionDidChangeAnimated,并且标志永远不会设置为NO)。

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


“快速修复”是在调用setVisibleMapRect 之前设置_mapNeedsPadding

- (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];
    }
}


但是,我不建议一开始就采用这种方法。

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

并且,不要在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;
//    }
//}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-05
    • 1970-01-01
    • 2010-11-30
    • 2011-03-17
    • 1970-01-01
    • 2018-09-26
    • 2013-11-14
    • 2016-11-24
    相关资源
    最近更新 更多