ios - Loop 不使用调度队列、iOS、Swift 完成循环

标签 ios loops grand-central-dispatch

我有一个运行循环的函数,它会为循环中的每个项目触发另一个函数,但它似乎没有像数组中的项目那样多次运行该函数。

这是我的函数。

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 - Loop 不使用调度队列、iOS、Swift 完成循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53343019/

相关文章:

ios - 将 gestureRecognizer 添加到 tableView 单元格

ios - UICollectionView - 如果选择了单元格,则不调用 didDeselectItemAtIndexPath

MySQL SQL : UPDATE while doing a JOIN on non-normalized table?

python - 加速 Pandas 中的多循环数据计算

ios - iOS-Grand Central Dispatch从dispatch_async中的 block 获取值(value)

ios - 如何防止在 GCD 中释放对象?

ios - CollectionView 滚动更改选定的单元格

ios - UIImagePickerController 禁用 iPhone 4S 人脸检测 (iOS 5.1)

java - 这些循环听起来是否正确,还是应该切换为for或while循环?

iphone - 异步图片加载闪烁?