gpt4 book ai didi

ios - 将自己作为委托(delegate)传递时的无限循环

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

我正在围绕 CLLocationManager 创建一个包装器,但我正在努力在我的 View Controller 中初始化包装器 LocationManager

我的 View Controller 执行以下操作:

class MyVC: UIViewController, CLLocationManagerDelegate {   

var locationManager: LocationManager? {
get {
if self.locationManager == nil {
self.locationManager = LocationManager(delegate: self)
}

return self.locationManager
}
set {
self.locationManager = newValue
}
}
...
}

想法是仅在实际需要时才初始化 LocationManager。但是我收到了一个 EXC_BAD_ACCESS(code=2... 并且当代码在 if self.locationManager == nil { 处中断时,我的主线程看起来像是一个无限循环。 .. 崩溃前约 175000 次。我的 LocationManager 将我的 View Controller 作为 CLLocationManagerDelegate 作为参数,并将其传递给实际的管理器。

import Foundation
import CoreLocation

class LocationManager {
let delegate: CLLocationManagerDelegate

var locationManager: CLLocationManager? {
get {
if self.locationManager == nil {
let locationManager = CLLocationManager()

locationManager.delegate = self.delegate
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation

self.locationManager = locationManager
}

return self.locationManager
}
set {
self.locationManager = newValue
}
}

init(delegate: CLLocationManagerDelegate) {
self.delegate = delegate
}

func start() {
if self.isAuthorized() {
self.locationManager!.startUpdatingLocation()
}
}

func stop() {
self.locationManager!.stopUpdatingLocation()
}

func isAuthorized() -> Bool {
switch CLLocationManager.authorizationStatus() {
case .Authorized:
return true
default:
return false
}
}

func requestAuthorization() {
self.locationManager!.requestAlwaysAuthorization()
}
}

self 的使用不允许在计算属性中像这样传递吗?

最佳答案

你想要的是像这样的惰性属性

lazy  var locationManager: LocationManager = {
let manager = LocationManager(delegate: self)
return manager
}()

同时将 LocationManager 类中的 locationManager 设置为惰性属性。

lazy var locationManager: CLLocationManager =  {
let locationManager = CLLocationManager()
locationManager.delegate = self.delegate
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
return locationManager
}()

你的错误在这里

  var locationManager: LocationManager? {
get {
if self.locationManager == nil {
self.locationManager = LocationManager(delegate: self)
}

return self.locationManager
}
set {
self.locationManager = newValue
}
}

locationManager的get方法中调用self.locationManager,会陷入死循环

关于ios - 将自己作为委托(delegate)传递时的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31307924/

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