2017-06-19 42 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

在上面的代码中,我得到错误:

self captured by a closure before all members were initialized

在构造在的reverseGeocodeLocation功能的线。

需要提及的是,在添加NSCoding零件之前,需要提供以下代码。

回答

0

使用[weak self]capture listclosure为:

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

谢谢伴侣!为我工作 –