ios - 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 调用中的块仅在函数的其余部分运行完后才执行。如何更改它以在循环的每次迭代中更新?
解决方案
代替
DispatchQueue.main.async {}
利用
DispatchQueue.main.sync {}
推荐阅读
- python - 如何将函数动态添加到类并保留函数在类中返回的内容?
- python - How can I set the diagonal of an N-dim tensor to 0 along given dims?
- c# - C# Word.Interop 更改 ContentControl DropDownList 的文本
- netlogo - 如何纠正错误:找不到没有数字的列表的平均值
- r - 如何根据另一行中的范围对 R 中的列表进行条件子集化
- asp.net - 文件已下载但其他按钮随后被禁用并且不会在 asp.net 中触发
- google-chrome - 如果消息泛滥,F8/pause 在 Chrome DevTools 中不起作用
- javascript - 根据范围参数可以从数字组成多少组
- xpages - Xpages - 通过按钮单击时 JS 代码无法执行
- postgresql - 获取每个季度的第一条实时记录