在单独的类中实现CLLocationManagerDelegate的内存错误

时间:2015-02-05 23:54:55

标签: ios swift cllocationmanager

我尝试将CLLocationManagerDelegate实现移到单独的类(文件)中,以免混淆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]!) {
        // …
    }

}

1 个答案:

答案 0 :(得分:1)

代表通常很弱,所以没有对象保留您的代理,这是导致内存访问错误的原因。

你应该做类似的事情:

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]!) {
    // …
}

}