GoogleMaps iOS SDK GMSMapView Class 已取消分配

GoogleMaps iOS SDK GMSMapView Class Deallocated

我正在努力将 GoogleMaps iOS SDK 集成到我的项目中,但我不断收到此错误:

'NSInternalInconsistencyException' 'An instance 0x7fea5e93e210 of class GMSMapView was deallocated while key value observers were still registered with it. Current observation info:

这是我的视图控制器代码:

import UIKit
import GoogleMaps

class ViewController: UIViewController, CLLocationManagerDelegate, GMSMapViewDelegate {

var locationManager = CLLocationManager()

var didFindMyLocation = false

let mapView = GMSMapView()

override func viewDidLoad() {
    super.viewDidLoad()

    let mapView = GMSMapView()


    locationManager.delegate = self
    locationManager.requestWhenInUseAuthorization()

    let camera: GMSCameraPosition = GMSCameraPosition.cameraWithLatitude(37.61729,longitude: -122.38229, zoom: 18)

    mapView.camera = camera

    mapView.delegate = self

    mapView.addObserver(self, forKeyPath: "myLocation", options: NSKeyValueObservingOptions.New, context: nil)
}

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    if !didFindMyLocation {
        let myLocation: CLLocation = change![NSKeyValueChangeNewKey] as! CLLocation
        mapView.camera = GMSCameraPosition.cameraWithTarget(myLocation.coordinate, zoom: 18.0)
        mapView.settings.myLocationButton = true

           didFindMyLocation = true
        }
    }

}

正如它所说:"key value observers were still registered with it",这实际上是在抱怨您没有注销 KVO 观察器。

KVO,在这个意义上,有点像 NSNotification - 如果你在 viewDidLoad: 中注册了一个观察者,你需要在 viewDidDisappear: 中删除观察者或 dealloc.

在您的情况下,尝试添加 dealloc 功能并使用 removeObserver:forKeyPath:context: 取消订阅 KVO。在 mattt 的 KVO 文章中阅读更多内容 here

Swift 3

deinit {
            mapView.removeObserver(self, forKeyPath: "myLocation")
}