gpt4 book ai didi

ios - observeValueForKeyPath 在 swift 中崩溃应用程序

转载 作者:搜寻专家 更新时间:2023-11-01 05:53:42 25 4
gpt4 key购买 nike

我是 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:change:context: 消息但未处理。关键路径:myLocation

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

最佳答案

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

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

正确的声明是这样的:

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

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

Xcode autocomplete

关于ios - observeValueForKeyPath 在 swift 中崩溃应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35094239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com