CLLocationManager.authorizationStatus 结果 EXC_BAD_ACCESS 代码=2

CLLocationManager.authorizationStatus results in EXC_BAD_ACCESS code=2

我的第一个应用程序到目前为止运行良好,如果允许定位服务的话。

只要我特别禁用此应用的定位服务(飞行模式,以及通常禁用的定位服务都按预期工作)。

代码如下:

    func locationServices()->Bool{
    if CLLocationManager.locationServicesEnabled() {
        switch(CLLocationManager.authorizationStatus()) {
        case .NotDetermined, .Restricted, .Denied:
            return false
        case .AuthorizedAlways, .AuthorizedWhenInUse:
            return true
        }
    } else {
        return false
    }

}

从 viewDidLoad 调用:

    override func viewDidLoad() {
    super.viewDidLoad()

    txtNotes.delegate = self
    datePicker.maximumDate = NSDate()
    if (inc != nil) {
        let Dateformatter = NSDateFormatter()
        Dateformatter.dateStyle = NSDateFormatterStyle.MediumStyle
        navigationItem.title = Dateformatter.stringFromDate((inc?.date)!)
        datePicker.date = (inc?.date)!
        txtNotes.text = inc?.notes
        ratingControl.rating = (inc?.rating)!
        lblAccuracy.text = inc?.geoloc
        self.location = inc?.geocor
    }
    else {
        if(locationServices()){
        self.locationManager = CLLocationManager()
        locationManager!.delegate = self
        locationManager!.requestWhenInUseAuthorization()
        locationManager!.desiredAccuracy = kCLLocationAccuracyBest
        locationManager!.startUpdatingLocation()

        }
        else{
            lblAccuracy.text = "Location Services Disabled"
            let alertController = UIAlertController(
                title: "Location Services Disabled",
                message: "Please allow this application to use location services",
                preferredStyle: .Alert)

            let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
            alertController.addAction(cancelAction)

            let openAction = UIAlertAction(title: "Open Settings", style: .Default) { (action) in
                if let url = NSURL(string:UIApplicationOpenSettingsURLString) {
                    UIApplication.sharedApplication().openURL(url)
                }
            }
            alertController.addAction(openAction)
            self.presentViewController(alertController, animated: true, completion: nil)
            viewDidLoad()
        }
    }
}

访问一个尚未初始化的委托不是一个聪明的主意...

访问前初始化解决了我的问题。