gpt4 book ai didi

ios - 线程安全队列

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

我正在执行 20 个具有不同 URL 的数据任务,并用结果填充一个数组,但在函数结束时,尽管使用相同的队列,我仍然没有得到最终数组。

    class func getImages(photos:[Photo]){
var images:[UIImage?] = []
let arrayQueue = DispatchQueue(label: "imagesQueue",attributes: .concurrent)
for i in 0...20{
let url = EndPoints.getImage(farm: photos[i].farm, server: photos[i].server, id: photos[i].id, secret: photos[i].secret).url
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
arrayQueue.async(flags: .barrier) {
let image = UIImage(data: data!)!
images.append(image)
}
}
task.resume()
}
arrayQueue.sync {
print(images.count)
}
}

这个函数应该打印 21,但是它打印了零。

最佳答案

当然是因为 函数的结束 不是时间线的结束。方法末尾的 print 行在数据任务的任何结果添加到队列之前立即执行。

需要DispatchGroupnotify闭包在所有任务完成后执行。

class func getImages(photos:[Photo]) {
var images:[UIImage] = [] // Why optional?
let group = DispatchGroup()
let arrayQueue = DispatchQueue(label: "imagesQueue", attributes: .concurrent)
for i in 0...20{
let url = EndPoints.getImage(farm: photos[i].farm, server: photos[i].server, id: photos[i].id, secret: photos[i].secret).url
group.enter()
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
arrayQueue.async(flags: .barrier) {
let image = UIImage(data: data!)!
images.append(image)
group.leave()
}
}
task.resume()
}
group.notify(queue: arrayQueue) {
print(images.count)
}
}

请注意,当发生错误时,您的代码会可靠地崩溃...

而您的自定义队列实际上是多余的,您正在执行 21 任务

关于ios - 线程安全队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56199349/

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