gpt4 book ai didi

ios - 为什么 .geocodeAddressString 不改变外部变量?

转载 作者:行者123 更新时间:2023-11-28 08:38:09 24 4
gpt4 key购买 nike

我有一个外部变量 chooseCoordinates,它的类型是 CLLocationCoordinate2D。这个 var 需要保存来自 geocodeAddressString 闭包的坐标,但显然,它不会改变。

我想请教一下,如何让这个真正的闭包存储数据,这样我就可以将它解析到另一个viewController

var chooseCoordinates = CLLocationCoordinate2D()
////////////

let geocoder = CLGeocoder()

geocoder.geocodeAddressString(sender.text!, completionHandler: { (placemarks, error) -> Void in

if(error != nil) {
print("\(error)")
}

if let placemark = placemarks?.first {
let coordinates: CLLocationCoordinate2D = placemark.location!.coordinate
self.chooseCoordinates = coordinates
}
})

最佳答案

geocodeAddressString 异步运行(即,即使该方法立即返回,它的 completionHandler 闭包也可能稍后调用)。那么,您确定它没有改变,或者只是在您尝试使用 chooseCoordinates 时没有改变?您应该从闭包(或 chooseCoordinatesdidSet)中启动 UI 或任何更新,而不是立即这样做。我们看不到您如何使用 chooseCoordinates,因此很难比这更具体。

例如:

geocoder.geocodeAddressString(sender.text!) { placemarks, error in
if error != nil {
print(error!)
}

if let placemark = placemarks?.first {
let coordinates: CLLocationCoordinate2D = placemark.location!.coordinate
self.chooseCoordinates = coordinates
// call the method that uses `chooseCoordinates` here
}
}

// don't try to use `chooseCoordinates` here, as it hasn't been set yet.

或者,您可以自己使用 completionHandler 模式:

@IBAction func didEndEditingTextField(sender: UITextField) {
geocodeAddressString(sender.text!) { coordinate, error in
self.chooseCoordinates = coordinate
// trigger whatever the next step is here, or in the `didSet` of `chooseCoordinates`
}

// don't try to use `chooseCooordinates` here
}

var chooseCoordinates: CLLocationCoordinate2D? // you probably should make this optional

let geocoder = CLGeocoder()

/// Geocode string
///
/// - parameter string: The string to geocode.
/// - parameter completionHandler: The closure that is called asynchronously (i.e. later) when the geocoding is done.

func geocodeAddressString(string: String, completionHandler: (CLLocationCoordinate2D?, NSError?) -> ()) {
geocoder.geocodeAddressString(string) { placemarks, error in
if error != nil {
print(error!)
}

if let placemark = placemarks?.first {
completionHandler(placemark.location!.coordinate, error)
} else {
completionHandler(nil, error)
}
}
}

关于ios - 为什么 .geocodeAddressString 不改变外部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37167075/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com