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

Can't perform action in background and update progressView in mainThread

我有这个方法:

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 块内的值总是结果为 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)
}