gpt4 book ai didi

ios - Swift:在for循环中调用完成处理程序方法

转载 作者:行者123 更新时间:2023-11-28 06:33:28 27 4
gpt4 key购买 nike

我想了解其中包含完成处理程序方法的 for 循环的行为。

请参阅下面的示例,其中我试图获取 2 个地址的纬度/经度坐标。

let addressArray = ["1 Infinite Loop, Cupertino", "809, Harvard Ave, Sunnyvale, CA - 94087"]
var coordinatesArray = [CLLocationCoordinate2D]()

for i in 0 ..< addressArray.count {
print(i)
let address = addressArray[i]
geocoder.geocodeAddressString(address, completionHandler: {(placemarks, error) -> Void in
print("Address = \(address)");
if let placemark = placemarks?.first {
let coordinate = placemark.location?.coordinate
self.coordinatesArray.append(coordinate!)
}
})
}

// Do something here after that that

输出是这样的

0
1
Address = 1 Infinite Loop, Cupertino

我想知道为什么代码中没有打印另一个地址。第二个 for 循环是否不调用 geocodeAddressString 方法。假设 for 循环结束后应用程序执行还没有结束,我做了很多其他事情。

最佳答案

说明:

  • 有一个 for 循环运行 N 次 (addressArray.count)。
  • 在每次迭代期间,都会提出地理编码请求。
  • 获取地点标记需要一些时间。
  • 这是一个异步方法,因此它不会阻止执行(这意味着循环会继续运行并且不会等到地理请求完成)。
  • 当特定迭代的地理编码请求完成时,它的完成处理程序将被执行。

问题:

  • 由于无法保证完成顺序,所以最好使用字典而不是数组。
  • 不要使用数组,因为完成的顺序可能不是连续的。
  • 例如,第一个请求可能会在第二个请求完成后完成。

解决方案:

  • 对于给定的整数索引,coordinates[index] 将对应于 addressArray[index]

代码(建议修复):

class Test {

let geocoder = CLGeocoder()

//Better use a dictionary instead of an array
var coordinates = [Int: CLLocationCoordinate2D]()

func f1() {

for i in 0 ..< addressArray.count {
print(i)
let address = addressArray[i]

geocoder.geocodeAddressString(address) {placemarks, error in
print("Address = \(address)");
if let placemark = placemarks?.first {
let coordinate = placemark.location?.coordinate

self.coordinates[i] = coordinate
}
}
}
}
}

关于ios - Swift:在for循环中调用完成处理程序方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39655032/

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