我想在一个地方删除我的地图的所有叠加层,我尝试了不同的方式,但它从来没有工作.
最后尝试我[self.mapView removeOverlays:self.mapView.overlays];它仍然不起作用.任何想法如何删除这些叠加?
谢谢.
更新1
我有错误:malloc:***错误的对象0x5adc0c0:指针被释放没有分配
***在malloc_error_break中设置一个断点来进行调试
我想我知道为什么,但不知道如何解决它?
以下是我需要在mapView上绘制另一行的代码:
- // Create a c array of points.
- MKMapPoint *pointsArray = malloc(sizeof(CLLocationCoordinate2D) * 2);
- // Create 2 points.
- MKMapPoint startPoint = MKMapPointForCoordinate(CLLocationCoordinate2DMake(oldLatitude,oldLongitude));
- MKMapPoint endPoint = MKMapPointForCoordinate(CLLocationCoordinate2DMake(newLatitude,newLongitude));
- // Fill the array.
- pointsArray[0] = startPoint;
- pointsArray[1] = endPoint;
- // Erase polyline and polyline view if not nil.
- if (self.routeLine != nil) {
- [_routeLine release];
- self.routeLine = nil;
- }
- if (self.routeLineView != nil) {
- [_routeLineView release];
- self.routeLineView = nil;
- }
- // Create the polyline based on the array of points.
- self.routeLine = [MKPolyline polylineWithPoints:pointsArray count:2];
- // Add overlay to map.
- [self.mapView addOverlay:self.routeLine];
- // clear the memory allocated earlier for the points.
- free(pointsArray);
- // Save old coordinates.
- oldLatitude = newLatitude;
- oldLongitude = newLongitude;
所以我释放了以前的叠加层的routeLine对象.所以当我试图删除它,它崩溃,因为它已被释放.
- - (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
- {
- MKOverlayView* overlayView = nil;
- if(overlay == _routeLine) {
- // If we have not yet created an overlay view for this overlay,create it now.
- if(self.routeLineView == nil) {
- self.routeLineView = [[[MKPolylineView alloc] initWithPolyline:_routeLine] autorelease];
- self.routeLineView.fillColor = [UIColor blueColor];
- self.routeLineView.strokeColor = [UIColor blueColor];
- // Size of the trace.
- self.routeLineView.lineWidth = routeLineWidth;
- }
- overlayView = self.routeLineView;
- }
- return overlayView;
- }
如果你们知道如何解决这个问题,从MKMapView中删除所有的叠加层就会很棒!
更新2
我试图没有释放我的routeLine和routeLineView对象,它现在工作.似乎也没有泄漏.所以现在我这样做:
- // Erase polyline and polyline view if not nil.
- if (self.routeLine != nil) {
- //[_routeLine release];
- self.routeLine = nil;
- }
- if (self.routeLineView != nil) {
- //[_routeLineView release];
- self.routeLineView = nil;
- }
解决方法
当您调用removeOverlays:时,地图视图将释放MKOverlay和MKOverlayView对象.
您在_routeLine和_routeLineView中持有您自己的引用.
removeOverlays:被调用后,变量将指向已经释放的内存.当您重新创建折线时,您将被过度释放,从而导致崩溃.
- if (_routeLine != nil) {
- [_routeLine release]; // <-- remove this
- self.routeLine = nil;
- }
- if (_routeLineView != nil) {
- [_routeLineView release]; // <-- remove this
- self.routeLineView = nil;
- }