observeValueForKeyPath在swift中崩溃应用程序

时间:2016-01-29 21:19:41

标签: ios swift

我对iOS开发非常陌生,并试图解决为什么我的应用程序崩溃了SIGABRT的消息。我正在关注如何实施Google Maps SDK的教程(link),据我所知,我有相同的代码。

我的代码:

@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:更改:context:收到消息但未处理。 关键路径:myLocation

有人可以告诉我我做错了什么吗?

1 个答案:

答案 0 :(得分:6)

问题是您尚未正确声明observeValueForKeyPath(_:ofObject:change:context:)。您的方法需要keyPathofObjectchange的错误参数类型。

您没有声明方法override这一事实是一个线索:如果您使用正确的类型声明它,编译器会告诉您它也需要声明override。 (它也会告诉你,你不能声明它private,因为它是public中的NSObject。)

正确的声明如下:

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?,
    change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>)

如果您刚开始在类范围内键入方法名称,Xcode将提供自动填充正确的声明:

Xcode autocomplete