gpt4 book ai didi

ios - 为什么我的 for 循环的索引在使用 grand dispatch 时会增加

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

我正在使用此方法在我的图像上显示图像,但是当它进入调度方法时,索引会增加。意味着当 i 为 1 时它设置为 2。请让我知道是什么问题。

谢谢。

for var i = 0 ; i<featuredCards.count ; i++ {

print("INDEXxxxxxxxxxxxx",i)
if i >= self.cardFeatruedTitlesCollection.count {
break
}

if photoModel.photoURL == featuredCards[i].cardPreviewImages[safe:0]?.photoURL {

dispatch_async(dispatch_get_main_queue(), { () -> Void in

if let path = photoModel.photoPath {

if let image : UIImage = photoModel.getThumbnailPhotoWithPath(path) {

if let imageView = self.cardFeaturedImagesCollection[safe:i] {
imageView.image = image
}

}
}
})
}
}

最佳答案

您正在循环中访问主队列,这不是一个好主意,因为分派(dispatch) block 将在循环迭代完成后执行,这就是它获得增量值的原因。

可以通过两种方式解决

  1. 使用__ block 变量
  2. 将 for 循环放在主队列 block 中,如下所示:

试试这个

dispatch_async(dispatch_get_main_queue()) {

for var i = 0 ; i<featuredCards.count ; i++ {

print("INDEXxxxxxxxxxxxx",i)
if i >= self.cardFeatruedTitlesCollection.count {
break
}

if photoModel.photoURL == featuredCards[i].cardPreviewImages[safe:0]?.photoURL {


if let path = photoModel.photoPath {

if let image : UIImage = photoModel.getThumbnailPhotoWithPath(path) {

if let imageView = self.cardFeaturedImagesCollection[safe:i] {
imageView.image = image
}

}
}
}
}
}

编辑:如果您使用的是 swift 3,那么您应该使用以下语法:

DispatchQueue.main.async { 
//Your For Loop
}

关于ios - 为什么我的 for 循环的索引在使用 grand dispatch 时会增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38713225/

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