我搜索了所有可能的解决方案,但找不到确切的解决方案。我的问题是:我正在使用导航控制器和带有GMSMapView的viewcontroller。当我从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
}
}
答案 0 :(得分:0)
我已经弄明白了这个问题。实际上我担心的是我使用removeObserver(self,forKeyPath:&#34; myLocation&#34;,context:nil)而不是mapView.removeObserver(self,forKeyPath:&#34; myLocation&#34;,context:nil)< / p>
答案 1 :(得分:0)
针对Swift 3.2+的基于封闭的新KVO是这样的:
class myCustomView: UIView {
let camera = GMSCameraPosition(target: CLLocationCoordinate2D(latitude: 52.5067614, longitude: 13.2846524), zoom: 10, bearing: 0, viewingAngle: 0)
lazy var mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
private var observation: NSKeyValueObservation?
func startObserving() {
self.observation = self.mapView.observe(\.myLocation, options: [.new, .old], changeHandler: { _, change in
guard let newLocation = change.newValue else { return }
//Do something with newlocation
})
}
}
随时随地调用startObserving()
函数。
使观察者无效不是强制性的,您可以让它超出范围。当您想使其无效时,只需执行以下操作:
self.observation?.invalidate()