我在Swift 2.0中編寫了以下函數來添加一個使用CLGeocoder()
來解析給定座標的位置名稱的地圖註釋。我使用defer
塊來獲得解析的位置名稱,但是,延遲塊似乎在閉合完成之前完成。下面是我的代碼:Swift 2:在閉包在相同函數中完成之前執行了defer塊
func addAnnotation(gestureRecognizer: UIGestureRecognizer) {
var locationNameStr = ""
defer {
let newPin = Pin(dictionary: locationDictionary, context: sharedContext)
newPin.name = locationNameStr
do {
//persist the new pin to core data
try sharedContext.save()
showPinOnMap(newPin)
} catch let error as NSError {
print("error saving the new pin in context")
}
}
// use CLGeocoder to resolve the location name as title of the annotation
CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: newCoordinate.latitude, longitude: newCoordinate.longitude), completionHandler: {(placemarks, error) -> Void in
if error != nil {
print("reverse geocoding failed with error: \(error)")
//return
} else if placemarks!.count > 0 {
let firstPlace = placemarks![0] as CLPlacemark
if firstPlace.country != nil {
locationNameStr = "a place in \(firstPlace.country!)"
}
else if firstPlace.locality != nil {
locationNameStr = "a place in \(firstPlace.locality!)"
}
print("location name: \(locationNameStr)")
}
})
}
這是正確和正確的行爲。你忘了問一個問題。 –