我正在获取用户位置,我已经创建了单例类来在需要时获取用户位置。但它正在创造保留周期。如果我使用LocationManager类,则不调用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方法。 还有其他更好的方法吗?这样保留周期就不会创造。
答案 0 :(得分:1)
LocationManager
课程本身似乎没有任何错误,但您对onSuccessBlock
传递的onFailedBlock
和getUserCurrentLocation
有强烈的引用。您从WKINterfaceController
班级致电的功能。如果您在这些区块中保留self
,则LocationManager
会强烈引用您的WKInterfaceController
课程,因此deinit
不会被调用。你能把WKInterfaceController
的代码放进去吗?然后我们可以说更多。
编辑:是的,您在self
中抓取weak
为onSuccessBlock
,但onFailedBlock
强烈抓取[weak self] in
。如果您将onFailedBlock
语句放在jmeter -JthreadNum=10 -t myJmx.jmx
的开头,它应该有效。