2017-06-19 123 views
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

答えて

0

使用[weak self]capture listとして:

CLGeocoder().reverseGeocodeLocation(self.placeCoordinate, completionHandler: {[weak self] (placemarks, error) -> Void in 
      //... 
     }) 
+0

あなたはそれが何であるかを説明できますか? –

+0

保持サイクルを避けるために、自己が弱くなる。自己はクロージャによってキャプチャされるので、自己が初期化されていない場合でも自己参照を保持する可能性があり、したがってアプリケーションがクラッシュする可能性があります。だから、これを避けるために、自己への弱い参照が使われます。弱参照の詳細については、https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html#//apple_ref/doc/uid/TP40014097-CH20-ID48 – PGDev

+0

ありがとうございますメイト! –

関連する問題