[英]Why deinit is not called when I pop/self.dismiss my WKInterfacecontroller
我正在獲取用戶位置,我創建了單例類以在需要時獲取用戶位置。 但它正在創造保留周期。 如果我使用LocationManager類,則不會調用deint。 如果我不使用此類,則可以按預期正確地調用此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
類本身中,似乎沒有什么錯,但是您持有對從WKINterfaceController
類調用的getUserCurrentLocation
函數中傳遞的onSuccessBlock
和onFailedBlock
的強引用。 如果您將self
保留在這些塊中,則LocationManager
將強烈引用WKInterfaceController
類,因此不會調用deinit
。 您可以WKInterfaceController
的代碼嗎? 然后我們可以說更多。
編輯:是的,您在onSuccessBlock
捕獲self
為weak
,但在onFailedBlock
捕獲self
為weak
。 如果在onFailedBlock
的開始處將[weak self] in
語句中,則它應該可以工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.