【发布时间】:2015-07-19 04:26:50
【问题描述】:
我已经搜索了所有可能的解决方案,但找不到确切的解决方案。我的问题是:我正在使用带有 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
}
}
【问题讨论】:
-
如果你在 viewWillAppear: 中注册,使用 viewWillDisappear 移除观察者。如果您在 viewDidLoad 中注册,请使用 deinit 取消注册观察者。始终使用计数器部分进行注册和注销,这应该没问题。
-
@GeneratorOfOne :感谢您宝贵的时间。我已经弄清楚了这个问题。实际上,我担心的是我使用 removeObserver(self, forKeyPath: "myLocation", context: nil) 而不是 mapView.removeObserver(self, forKeyPath: "myLocation", context: nil)
-
谢谢@Sandeep
-
@AmritSidhu:您在评论中的回答对我帮助很大。您应该将您的解决方案添加为答案而不是评论,以便人们可以轻松找到解决方案。
标签: ios swift xcode6 key-value-observing gmsmapview