4

我已经搜索了所有可能的解决方案,但找不到确切的解决方案。我的问题是:我正在使用带有 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
    }
}
4

2 回答 2

1

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()
于 2019-04-10T10:33:13.703 回答
0

I have figured out the issue. Actually the concern was that I used removeObserver(self, forKeyPath: "myLocation", context: nil) instead of mapView.removeObserver(self, forKeyPath: "myLocation", context: nil)

于 2017-09-03T16:39:09.087 回答