自己被关闭错误捕获
问题描述:
var myGroup = DispatchGroup()
class Place: NSObject, NSCoding {
// Properties
var placeCoordinate: CLLocation!
var placeName: String!
// Methods
required init(coder aDecoder: NSCoder) {
self.placeCoordinate = aDecoder.decodeObject(forKey: "placeCoordinate") as! CLLocation
self.placeName = aDecoder.decodeObject(forKey: "placeName") as! String
}
init(latitude: CLLocationDegrees, longitude: CLLocationDegrees) {
myGroup.enter()
self.placeCoordinate = CLLocation(latitude: latitude, longitude: longitude)
CLGeocoder().reverseGeocodeLocation(self.placeCoordinate, completionHandler: { (placemarks, error) -> Void in
if error != nil {
self.placeName = "Unrecognized"
print(error!)
} else {
if let placemark = placemarks?[0] {
self.placeName = (placemark.addressDictionary!["FormattedAddressLines"] as! [String])[1]
myGroup.leave()
}
}
})
}
func encode(with aCoder: NSCoder) {
aCoder.encode(placeCoordinate, forKey: "placeCoordinate")
aCoder.encode(placeName, forKey: "placeName")
}
}
我已经建立了这个类,它使用了一个async
函数,如你所见。自己被关闭错误捕获
我想保存这个对象的数组在UserDefaults
。我发现在UserDefaults中保存自定义对象是不可能的,所以现在我试着用NSCoding
。
在上面的代码中,我得到错误:
self captured by a closure before all members were initialized
在构造在的reverseGeocodeLocation
功能的线。
需要提及的是,在添加NSCoding
零件之前,需要提供以下代码。
答
使用[weak self]
capture list
在closure
为:
CLGeocoder().reverseGeocodeLocation(self.placeCoordinate, completionHandler: {[weak self] (placemarks, error) -> Void in
//...
})
你能解释这是什么? –
为了避免保留周期,自我弱化。由于自我被关闭捕获,因此它可能会保留对自我的引用,即使自我被取消初始化,因此应用程序可能会崩溃。所以,为了避免这种对自我的弱引用被使用。有关弱引用的更多信息,请参阅:https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html#//apple_ref/doc/uid/TP40014097-CH20-ID48 – PGDev
谢谢伴侣!为我工作 –