在单独 class 中实现 CLLocationManagerDelegate 时出现内存错误

Memory error implementing CLLocationManagerDelegate in a separate class

我尝试将 CLLocationManagerDelegate 实现移动到一个单独的 class(文件),以免弄乱 ViewController 代码,但每次都会出现内存错误 EXC_BAD_ACCESS (code=1, address=0xc) 我在这里做错了什么?

这是我的实现:

class ViewController: UIViewController {

    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.delegate = LocationManagerDelegate()
        // >=iOS8
        if (locationManager.respondsToSelector(Selector("requestWhenInUseAuthorization"))) {
            locationManager.requestWhenInUseAuthorization()
        } else {
            locationManager.startUpdatingLocation()
        }
    }

}

class LocationManagerDelegate: NSObject, CLLocationManagerDelegate {

    func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        // …
    }

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        // …
    }

}

委托通常是弱的,因此没有对象保留您的委托,这就是您的 Bad memory access 错误的原因。

你应该做类似的事情:

class ViewController: UIViewController {

let locationManager = CLLocationManager()

//instantiate and hold a strong reference to the Core Location Manager Delegate
//Normally you don't need this because the delegate is self

let locationManagerDelegate = LocationManagerDelegate() 


override func viewDidLoad() {
    super.viewDidLoad()

    locationManager.delegate = self.locationManagerDelegate
    // >=iOS8
    if (locationManager.respondsToSelector(Selector("requestWhenInUseAuthorization"))) {
        locationManager.requestWhenInUseAuthorization()
    } else {
        locationManager.startUpdatingLocation()
    }
}

}

class LocationManagerDelegate: NSObject, CLLocationManagerDelegate {

func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    // …
}

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    // …
}

}