我已经搜索了所有可能的解决方案,但找不到确切的解决方案。我的问题是:我正在使用带有 GMSMapView 的导航控制器和视图控制器。当我从 GMSMapView 导航到其他视图时,应用程序崩溃并显示“类 GMSMapView 的实例 0x7f9b79c53c20 已被释放,而键值观察者仍向其注册”。
但是,如果我尝试在 viewwilldisappear 或 deinit 中删除观察者,应用程序会再次崩溃,并出现异常“无法从中删除关键路径“myLocation”的观察者,因为它没有注册为观察者。
任何人都可以提供最佳解决方案。这是我的代码:
override func viewDidLoad() {
open.target = self.revealViewController()
open.action = "revealToggle:"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
locationManager.delegate = self
mapView.delegate = self
if (locationManager.respondsToSelector(Selector("requestWhenInUseAuthorization"))) {
locationManager.requestWhenInUseAuthorization()
}
mapView.myLocationEnabled = true
placesClient = GMSPlacesClient()
}
override func viewWillAppear(animated: Bool) {
mapView.addObserver(self, forKeyPath: "myLocation", options: NSKeyValueObservingOptions.New, context: nil)
}
deinit{
removeObserver(self, forKeyPath: "myLocation", context: nil)
}
override func viewWillDisappear(animated: Bool) {
// removeObserver(self, forKeyPath: "myLocation")
}
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if !didFindMyLocation {
let myLocation: CLLocation = change[NSKeyValueChangeNewKey] as CLLocation
mapView.camera = GMSCameraPosition.cameraWithTarget(myLocation.coordinate, zoom: 15.0)
mapView.settings.myLocationButton = true
didFindMyLocation = true
}
}