ios - 循环不使用调度队列、iOS、Swift 完成循环
<p><p>我有一个运行循环的函数,它为循环中的每个项目触发另一个函数,但它似乎没有像数组中的项目那样多次运行该函数。</p>
<p>这是我的功能。</p>
<pre><code>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)")
})
}
}
</code></pre>
<p>这是 consol 中的打印输出,如您所见,它首先打印循环开始,然后打印中间 1 次和结束 1 次,并在末尾附加一个项目,而不是像输入的一样 4。</p>
<blockquote>
<p>Tony items amount is 4</p>
<p>Tony begin loop</p>
<p>Tony begin loop</p>
<p>Tony begin loop</p>
<p>Tony begin loop</p>
<p>Tony mid loop</p>
<p>Tony array is with images person is </p>
<p>Tony items 2 amount is 1</p>
</blockquote></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>您那里的代码正在运行。问题似乎是 <code>sd_setImage</code> 只提供一次结果。</p>
<p><strong>如何测试</strong></p>
<p>如果你使用 <code>sd_setImage</code> 的测试实现如下,那么你会得到预期的结果:</p>
<pre><code>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!)
})
}
}
</code></pre></p>
<p style="font-size: 20px;">关于ios - 循环不使用调度队列、iOS、Swift 完成循环,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/53343019/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/53343019/
</a>
</p>
页:
[1]