2016-01-29 15 views
1

我對iOS開發非常陌生,並試圖圍繞爲什麼我的應用程序崩潰時出現SIGABRT消息。我正在沿着教程(link)瞭解如何實施Google Maps SDK,並且據我所知,我擁有相同的代碼。observeValueForKeyPath在swift中崩潰的應用程序

我的代碼:

@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',原因:':An -observeValueForKeyPath:ofObject:change:context:message已終止但未處理。 關鍵路徑:myLocation

有人能告訴我我做錯了什麼嗎?

回答

6

問題是您尚未正確聲明observeValueForKeyPath(_:ofObject:change:context:)。您的方法需要keyPath,ofObjectchange的錯誤參數類型。

事實上,你沒有聲明你的方法override是一個線索:如果你用正確的類型聲明它,編譯器會告訴你它還需要被聲明爲override。 (這也將告訴你,你不能將它聲明private,因爲它是publicNSObject。)

正確的聲明如下所示:

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

如果你剛開始請在類範圍的方法名稱,Xcode將提供自動完成正確的聲明:

Xcode autocomplete

+0

非常感謝!那樣做了。 – Amalie