为什么 label.text 更新没有反映在屏幕上?

Why isn't label.text update reflected on screen?

我有一个简单的测试应用程序,它向 NSOperationQueue 提交一些作业,然后等待它们完成。然后我有一个例程来检查队列中的作业数量,并应该更新屏幕上的值。同时它将值打印到控制台。控制台的工作方式完全符合我的预期,每十秒打印一个数字。数字减少到零,警报被触发。但是标签(进度)在任何阶段都不会从 "Hello".

改变

我有一种感觉,与其说它是我代码中的错误,不如说它是我对 Swift 理解中的一个大漏洞。请帮忙

我的代码:

Import UIKit

class TestUpload: UIViewController {


@IBOutlet weak var progress: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    progress.text = "Hello"

    // submit some jobs ….        
    // * I have omitted this code as I don't think it has a problem. * //

    let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), 10 * Int64(NSEC_PER_SEC))
    dispatch_after(time, dispatch_get_main_queue()) {

        self.showProgress()
    }

}

func showProgress() {

    while Int(session.operationQueue.operationCount) > 0 {
        sleep(10)
        print(session.operationQueue.operationCount)
        progress.text = String(session.operationQueue.operationCount)
    }

    let confirmUpload = UIAlertController(title: "Your Tasks have been performed.", message: "Congratulation!", preferredStyle: UIAlertControllerStyle.Alert)
    confirmUpload.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in  self.navigationController?.popViewControllerAnimated(true)}))

    presentViewController(confirmUpload, animated: true, completion: nil)


}

sleep() 不允许 UI 线程自行更新,因此您必须在异步块中更新它:-

while Int(session.operationQueue.operationCount) > 0 {
            sleep(10)
            print(session.operationQueue.operationCount)

 ///add this line
          dispatch_async(dispatch_get_main_queue()) {
            progress.text = String(session.operationQueue.operationCount)
          }
    }

UI 在 showProgress 方法结束之前不会更新。所以你可以做下面这样的事情,如果那是你想要的,。

作为不同的线程调用,

NSThread.detachNewThreadSelector("showProgress", toTarget: self, withObject: nil)

然后在主线程

上更新UI
func showProgress() {

    while Int(session.operationQueue.operationCount) > 0 {
        sleep(10)
        print(session.operationQueue.operationCount)

        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            progress.text = String(session.operationQueue.operationCount)
        })
    }

    dispatch_async(dispatch_get_main_queue(), { () -> Void in
    let confirmUpload = UIAlertController(title: "Your Tasks have been performed.”, message: “Congratulation!”, preferredStyle: UIAlertControllerStyle.Alert)
        confirmUpload.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in  self.navigationController?.popViewControllerAnimated(true)}))

        presentViewController(confirmUpload, animated: true, completion: nil)
    })


}

运行 都在主线程中,即使您将其设为异步调度也无法解决您的问题