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
で試しています。 I上記のコードで
は、エラーを取得する:のreverseGeocodeLocation
機能の行で、コンストラクタで
self captured by a closure before all members were initialized
。
NSCoding
の部分を追加する前に、次のコードが正常に機能していることが必要です。 closure
で
あなたはそれが何であるかを説明できますか? –
保持サイクルを避けるために、自己が弱くなる。自己はクロージャによってキャプチャされるので、自己が初期化されていない場合でも自己参照を保持する可能性があり、したがってアプリケーションがクラッシュする可能性があります。だから、これを避けるために、自己への弱い参照が使われます。弱参照の詳細については、https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html#//apple_ref/doc/uid/TP40014097-CH20-ID48 – PGDev
ありがとうございますメイト! –