【问题标题】:I don't understand Property 'self.heading' not initialized at super.init call error in my code我不明白 Property 'self.heading' not initialized at super.init call error in my code
【发布时间】:2019-09-15 13:35:05
【问题描述】:

我创建了一个类来使用 CLLocationManagerDelegate 为我的 SwiftUI 应用程序获取当前标题,但出现 Property 'self.heading' not initialized at super.init call 错误。我不知道为什么。我认为我不需要指定参数,因为我的类在调用过程中不带任何参数?

我的 LocationManager 类:

class LocationManager: NSObject, CLLocationManagerDelegate, ObservableObject {

  var locationManager: CLLocationManager?
  var objectWillChange = PassthroughSubject<Void, Never>()

  @Published var heading: Double {
    willSet {
      objectWillChange.send()
    }
  }

  override init() {
    super.init()

    locationManager = CLLocationManager()
    locationManager!.delegate = self
    locationManager!.desiredAccuracy = kCLLocationAccuracyBest
    locationManager!.requestWhenInUseAuthorization()
  }

  func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
    self.heading = newHeading.trueHeading.degreesToRadians
  }

}

【问题讨论】:

    标签: swift cllocationmanager swiftui


    【解决方案1】:

    必须在初始化super之前初始化当前类的所有实例变量。

    所以在调用super.init() 之前给heading 添加一些初始值,比如:

    override init() {
        heading = 0 // Or anything you need
        super.init()
    
        locationManager = CLLocationManager()
        locationManager!.delegate = self
        locationManager!.desiredAccuracy = kCLLocationAccuracyBest
        locationManager!.requestWhenInUseAuthorization()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-27
      • 1970-01-01
      • 2022-06-28
      • 2019-04-16
      • 1970-01-01
      • 2020-11-10
      • 1970-01-01
      相关资源
      最近更新 更多