gpt4 book ai didi

ios - 无法在后台执行操作并在 mainThread 中更新 progressView

转载 作者:行者123 更新时间:2023-11-29 01:04:40 24 4
gpt4 key购买 nike

我有这个方法:

func stepThree() {
operation = "prDatas"
let entries = self.data.componentsSeparatedByString("|***|")
total = entries.count
for entry in entries {
++current
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
self.registerDB(entry)
})
}
status.setProgress(Float(current/total), animated: true)
finishAll()
}

我想执行registerDB函数并在完成后更新我的进度条。我测试了几种方法但从未成功


编辑 1

实现@Russell 命题,工作完美,但在dispatch_async block 内计算值总是结果为0

操作和多线程有问题吗?

方法:

func stepThree() {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
var current = 0
var total = 0
self.operation = "prDatas"
let entries = self.data.componentsSeparatedByString("|***|")
total = entries.count
for entry in entries {
++current
self.registerDB(entry)
dispatch_async(dispatch_get_main_queue(), {
print("value of 'current' is :" + String(current))
print("value of 'total' is :" + String(total))
print("Result is : " + String(Float(current/total)))
self.updateV(Float(current/total))
})
}
})
}

控制台输出:

value of 'current' is :71
value of 'total' is :1328
Result is : 0.0

最佳答案

您的代码将立即更新状态栏 - 因此作业不会完成。

您需要移动更新,以便它实际上遵循 registerDB 函数,然后您必须在主线程上进行调用。这是一个示例 - 使用虚拟函数而不是函数调用,以便我可以确保它按预期工作

func stepThree()
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
let total = 5 // test data for demo
for entry in 0...total
{
// dummy function - just pause
sleep(1)
//self.registerDB(entry)

// make UI update on main queue
dispatch_async(dispatch_get_main_queue(),
{
self.setProgress(Float(entry)/Float(total))
})
}
})
}

func setProgress(progress : Float)
{
progressView.progress = progress
lblProgress.text = String(format: "%0.2f", progress)
}

关于ios - 无法在后台执行操作并在 mainThread 中更新 progressView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36553521/

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