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

时间:2016-04-11 15:53:19

标签: ios multithreading uiprogressview

我有这种方法:

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功能并在完成后更新我的progressBar。 我试过几次但从未成功

编辑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

1 个答案:

答案 0 :(得分:1)

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

您需要移动更新以使其实际跟随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)
}