[英]observeValueForKeyPath crashing app in swift
我对iOS开发非常陌生,并试图用SIGABRT消息来说明为什么我的应用程序崩溃。 我将按照教程( 链接 )进行操作,以了解如何实现Google Maps SDK,据我所知,我具有相同的代码。
我的代码:
@IBOutlet weak var mapView: GMSMapView!
let locationManager = CLLocationManager()
var didFindMyLocation = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
locationManager.requestWhenInUseAuthorization()
locationManager.delegate = self
mapView.addObserver(self, forKeyPath: "myLocation", options: NSKeyValueObservingOptions.New, context: nil)
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == CLAuthorizationStatus.AuthorizedWhenInUse {
mapView.myLocationEnabled = true
}
}
private 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: 10)
mapView.settings.myLocationButton = true
didFindMyLocation = true
}
}
当我添加最后一个函数observeValueForKeyPath时发生崩溃,我无法弄清原因。 我收到以下错误消息:
由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:':收到但未处理-observeValueForKeyPath:ofObject:change:context:消息。 关键路径:myLocation
有人可以告诉我我在做什么错吗?
问题是您没有正确声明observeValueForKeyPath(_:ofObject:change:context:)
。 您的方法期望keyPath
, ofObject
和change
参数类型错误。
您没有声明方法override
的事实是一个线索:如果您使用正确的类型声明了它,编译器会告诉您还需要声明它的override
。 (这还会告诉您,您不能将其声明为private
,因为它在NSObject
是public
的。)
正确的声明如下所示:
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?,
change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>)
如果您只是开始在类范围内键入方法名称,则Xcode将提供自动完成正确声明的方法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.