我有一个运行循环的函数,它为循环中的每个项目触发另一个函数,但它似乎没有像数组中的项目那样多次运行该函数。
这是我的功能。
func startLoop(completion: @escaping (_ finished: Bool) -> ()) {
print("Tony items amount is \(tempImgUrls.count)")
for item in tempImgUrls {
dispatchGroup.enter()
print("Tony begin loop")
let img = item["imgUrl"]
let name = item["name"]
downloadImages(img: img!, name: name!, completion: { (complete) in
print("Tony mid loop")
self.dispatchGroup.leave()
})
}
dispatchGroup.notify(queue: DispatchQueue.main) {
print("Tony end loop")
completion(true)
}
}
func downloadImages(img: String, name: String, completion: @escaping (_ finished: Bool) -> ()) {
imageShown.sd_setImage(with: URL(string: img), completed: { (image, error, cacheType, imageUrl) in
let personImg = image!
let personId = name
let post = Person(personImage: personImg, personId: personId)
self.finalImgUrls.append(post)
completion(true)
print("Tony array is with images person is \(self.finalImgUrls)")
print("Tony items 2 amount is \(self.finalImgUrls.count)")
})
}
}
这是 consol 中的打印输出,如您所见,它首先打印循环开始,然后打印中间 1 次和结束 1 次,并在末尾附加一个项目,而不是像输入的一样 4。
Tony items amount is 4
Tony begin loop
Tony begin loop
Tony begin loop
Tony begin loop
Tony mid loop
Tony array is with images person is [AppName.Person]
Tony items 2 amount is 1
您那里的代码正在运行。问题似乎是 sd_setImage
只提供一次结果。
如何测试
如果你使用 sd_setImage
的测试实现如下,那么你会得到预期的结果:
class SomeClass {
func sd_setImage(with url: URL?, completed: @escaping (UIImage?, Error?, String, URL) -> Void) {
let random = Double(arc4random()) / Double(UINT32_MAX)
DispatchQueue.main.asyncAfter(deadline: .now() + random, execute: {
completed(UIImage(), nil, "a", url!)
})
}
}
关于ios - 循环不使用调度队列、iOS、Swift 完成循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53343019/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |