gpt4 book ai didi

ios - 在单独的类中实现 CLLocationManagerDelegate 时出现内存错误

转载 作者:行者123 更新时间:2023-11-29 02:19:22 26 4
gpt4 key购买 nike

我尝试将 CLLocationManagerDelegate 实现移动到一个单独的类(文件)中,以免弄乱 ViewController 代码,但每次都出现内存错误 EXC_BAD_ACCESS (code= 1, 地址=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]!) {
// …
}

}

最佳答案

委托(delegate)通常很弱,因此没有对象保留您的委托(delegate),这就是导致错误内存访问错误的原因。

你应该做类似的事情:

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

}

关于ios - 在单独的类中实现 CLLocationManagerDelegate 时出现内存错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28356266/

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