我正在获取用户位置,我已经创建了单例类来在需要时获取用户位置。 但它正在创建保留周期。 如果我使用位置管理器类,则不调用 deint。 如果我不使用这个类,这个 de按预期正确调用了 init。
class LocationManager: NSObject, CLLocationManagerDelegate {
private var clLocationManager: CLLocationManager?
private var SuccessBlock:((_ latitude: String, _ longitude: String)->Void)?
private var OnFailedBlock:(()->Void)?
private var lat: String?
private var long: String?
static let shared: LocationManager = {
let instance = LocationManager()
return instance
}()
private override init() {
super.init()
}
private func invokeLocationManager() {
if self.clLocationManager == nil {
self.clLocationManager = CLLocationManager()
self.clLocationManager?.delegate = self
}
self.clLocationManager?.requestWhenInUseAuthorization()
self.clLocationManager?.startUpdatingLocation()
}
func getUserCurrentLocation(onSucessBlok onSucessBlock:@escaping (_ lat: String, _ long: String)->Void, onFailedBlok onFailedBlock:@escaping ()->Void) ->Void {
self.SuccessBlock = onSucessBlock
self.OnFailedBlock = onFailedBlock
self.invokeLocationManager()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.clLocationManager?.stopUpdatingLocation()
if locations.count > 0 {
let userLocation = locations[0]
self.long = String(userLocation.coordinate.longitude);
self.lat = String(userLocation.coordinate.latitude);
if self.SuccessBlock != nil {
self.SuccessBlock!(self.lat!, self.long!)
self.SuccessBlock = nil
}
} else {
if self.OnFailedBlock != nil {
self.OnFailedBlock!()
self.OnFailedBlock = nil
}
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
if self.OnFailedBlock != nil {
self.OnFailedBlock!()
self.OnFailedBlock = nil
}
}
}
从WKInterfaceController,我调用此方法
override func willActivate() {
super.willActivate()
self.getUserLocation()
}
private func getUserLocation() {
LocationManager.shared.getUserCurrentLocation(onSucessBlok: { [weak self] (lat, long) in
if CommonHelper.isStringValid(string: lat) && CommonHelper.isStringValid(string: long) {
self?.fillInfoToDictionary(value:lat, key: KLatitude, type: InfoType.Acceleration)
self?.fillInfoToDictionary(value:long, key: KLongitude, type: InfoType.Acceleration)
}
}, onFailedBlok: {
self.fillInfoToDictionary(value:"0", key: KLatitude, type: InfoType.Acceleration)
self.fillInfoToDictionary(value:"0", key: KLongitude, type: InfoType.Acceleration)
})
}
每次调用 WKInterface 的 willActivate 时,我都会调用此 getUserCurrentLocation 方法。还有其他更好的方法吗?这样保留周期就不会产生。
LocationManager
类本身似乎没有任何问题,但你持有对onSuccessBlock
和onFailedBlock
的强引用,该引用是在你从WKINterfaceController
类调用的getUserCurrentLocation
函数中传递的。如果您在这些块中保留self
,则LocationManager
将具有对WKInterfaceController
类的强引用,因此不会调用deinit
。你能把你的WKInterfaceController
的代码吗?然后我们可以说更多。
编辑:是的,您正在捕获self
weak
在onSuccessBlock
中,但在onFailedBlock
中强烈。如果您将[weak self] in
语句放在onFailedBlock
的开头,它应该可以工作。