首页 > 解决方案 > main.async 中的块仅在 global.async 块完成后执行

问题描述

我正在从我的库中调用一个函数,该函数应该更新应用程序中的一些 UI:

DispatchQueue.global().async {
    autoreleasepool {
        print("is main thread =", Thread.isMainThread)
        for i in 0..<data.count {
            for j in 0..<data[i].createArray.count {
                let dataObject = NSEntityDescription.insertNewObject(forEntityName: entity, into: context)

                // Parse the dictionary of keys/values returned from the synced array into an easily readable JSON file.
                let parsedData = json(from: data[i].createArray[j])
                DispatchQueue.main.async {
                    label?.text = "Syncing " + String(describing: j + 1) + " " + entity + "s out of " + String(describing: data[i].createArray.count)
                    print("is main thread =", Thread.isMainThread)

                    print(label?.text)
                }
            }
        }
    }
}

但是,main.async 调用中的块仅在函数的其余部分运行完后才执行。如何更改它以在循环的每次迭代中更新?

标签: iosswiftasynchronousgrand-central-dispatch

解决方案


代替

DispatchQueue.main.async {}

利用

DispatchQueue.main.sync {}

推荐阅读