2015-07-19 75 views
3

我已經搜索了所有可能的解決方案,但找不到確切的解決方案。我的問題是:我正在使用GMSMapView的導航控制器和視圖控制器。當我從GMSMapView導航到其他視圖時,該應用程序崩潰時出現了一個問題:「GMSMapView類的實例0x7f9b79c53c20已被釋放,而鍵值觀察者仍在其中註冊。」在GMSMapView中添加和刪除KVO「myLocation」的觀察者

但是,如果我嘗試刪除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 
    } 
} 
+1

如果您在viewWillAppear: viewWillDisappear刪除觀察者。如果您在viewDidLoad中註冊,請使用deinit取消註冊觀察者。始終使用櫃檯部分註冊和取消註冊,這應該沒問題。 – Sandeep

+2

@GeneratorOfOne:感謝您寶貴的時間。我已經想出了這個問題。其實關心的是我使用removeObserver(self,forKeyPath:「myLocation」,context:nil)而不是mapView.removeObserver(self,forKeyPath:「myLocation」,context:nil) –

+0

謝謝@Sandeep –

回答

0

我已經找到了問題。其實關心的是我使用removeObserver(self,forKeyPath:「myLocation」,context:nil)而不是mapView.removeObserver(self,forKeyPath:「myLocation」,context:nil)