Swift MKMapView有时会变为零并且应用程序崩溃

时间:2016-11-01 18:38:32

标签: ios swift mkmapview mapkit

我正在显示这样的地图:

//Map
    @IBOutlet var mapView: MKMapView!

    var location: String?

    override func viewDidLoad() {
        super.viewDidLoad()

        self.mapView.delegate = self

        if let location = location {
            let address = location
            let geocoder = CLGeocoder()
            geocoder.geocodeAddressString(address) { (placemarks, error) in
                if let placemarks = placemarks {
                    if placemarks.count != 0 {
                        let annotation = MKPlacemark(placemark: placemarks.first!)
                        self.mapView.addAnnotation(annotation)
                        let span = MKCoordinateSpanMake(0.1, 0.1)
                        let region = MKCoordinateRegionMake(annotation.coordinate, span)
                        self.mapView.setRegion(region, animated: false)
                    }
                }
            }
        }
    }

    //Fixing map memory issue
    override func viewWillDisappear(_ animated:Bool){
        super.viewWillDisappear(animated)
        self.applyMapViewMemoryFix()
    }

    //Fixing map memory issue
    func applyMapViewMemoryFix(){
        switch (self.mapView.mapType) {
        case MKMapType.hybrid:
            self.mapView.mapType = MKMapType.standard
            break;
        case MKMapType.standard:
            self.mapView.mapType = MKMapType.hybrid
            break;
        default:
            break;
        }
        self.mapView.showsUserLocation = false
        self.mapView.delegate = nil
        self.mapView.removeFromSuperview()
        self.mapView = nil
    }

如果我退出VC并快速返回几次,应用程序最终会崩溃,因为MKMapView变为零。

崩溃发生在 self.mapView.addAnnotation(注释)

我不知道为什么,但我的猜测是geocoder.geocodeAddressString尚未完成加载/搜索,如果我从VC退出足够快mapView变为零

1 个答案:

答案 0 :(得分:2)

您在self.mapView方法中将nil设置为viewWillDisappear。因此,在地理编码器完成之前,只要您离开视图控制器,您的应用就会崩溃。

只需在地理编码器块中添加nil的正确检查。

override func viewDidLoad() {
    super.viewDidLoad()

    self.mapView.delegate = self

    if let location = location {
        let address = location
        let geocoder = CLGeocoder()
        geocoder.geocodeAddressString(address) { (placemarks, error) in
            if let placemarks = placemarks {
                if placemarks.count != 0 {
                    if let mapView = self.mapView {
                        let annotation = MKPlacemark(placemark: placemarks.first!)
                        mapView.addAnnotation(annotation)
                        let span = MKCoordinateSpanMake(0.1, 0.1)
                        let region = MKCoordinateRegionMake(annotation.coordinate, span)
                        mapView.setRegion(region, animated: false)
                    }
                }
            }
        }
    }
}