2015-07-19 77 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)