1
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
零件之前,需要提供以下代碼。
你能解釋這是什麼? –
爲了避免保留週期,自我弱化。由於自我被關閉捕獲,因此它可能會保留對自我的引用,即使自我被取消初始化,因此應用程序可能會崩潰。所以,爲了避免這種對自我的弱引用被使用。有關弱引用的更多信息,請參閱:https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html#//apple_ref/doc/uid/TP40014097-CH20-ID48 – PGDev
謝謝伴侶!爲我工作 –