【问题标题】:Why is defer block executed before a closure finishes in the same function [closed]为什么在同一个函数中的闭包完成之前执行延迟块[关闭]
【发布时间】:2015-10-04 22:14:46
【问题描述】:

我编写了以下函数来添加地图注释,该注释使用CLGeocoder() 来解析给定坐标的位置名称。我使用defer 块来获取解析的位置名称。但是,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)")
        }
    })
}

【问题讨论】:

  • 这是正确和正确的行为。你忘了问一个问题。

标签: ios swift asynchronous deferred clgeocoder


【解决方案1】:

你误解了延迟块的作用。

当你退出当前作用域时,它是一段代码。

当您使用完成块执行异步方法时,它会立即返回并继续执行到下一行。被调用的方法获取您的完成块并将其保存以供以后使用。

然后您的方法完成并且执行超出了方法的范围。 defer 块被执行。稍后,异步方法完成它的后台工作并调用您传递给它的完成处理程序。使用在调用方法返回后总是发生的异步方法。

@fqdn 有正确的想法。将您的清理代码放在完成块中。那就是它所属的地方。

【讨论】:

    【解决方案2】:

    reverseGeocodeLocation(_:completionHandler:) 异步执行,因此 defer 块中的代码在调用 completionHandler 参数传递的闭包之前执行是有意义的

    您的defer 块中的代码是否有原因无法移入您的完成处理程序?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      • 2015-02-17
      • 2018-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多