当自己作为委托传递时的无限循环

时间:2015-07-09 04:04:50

标签: ios swift

我正在创建CLLocationManager的包装器,但我正在努力在视图控制器中初始化包装器LocationManager

我的视图控制器执行以下操作:

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将我的视图控制器作为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像这样传递?

1 个答案:

答案 0 :(得分:1)

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

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
    }
}

您在self.locationManager的get方法中调用locationManager,它将陷入死循环