why lable’s text can’t change, but can debug str?
i know queue.sync is excute in main thread,when i sleep in main thread。
class ViewController: UIViewController {
let queue = DispatchQueue(label: "queue", qos: .userInteractive)
let sem = DispatchSemaphore(value: 0)
@IBOutlet var label: UILabel!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
for _ in 0..<10 {
queue.sync {
Thread.sleep(forTimeInterval: 2)
let str = String(Int.random(in: 1...10))
debugPrint(str)
DispatchQueue.main.async {
self.label.text = str
}
}
}
}
}
2
Answers
You are blocking yourself. Consider:
queue.sync
while on the main thread. So now the main thread is blocking waiting forqueue
to finish; no code can run on the main thread.DispatchQueue.main.async
, asking for the closure (*
) to be performed on the main thread. But that, as we have just said, is impossible; the main thread is blocking, and no code can run on it.As for your debugPrint, it is on
queue
, not the main thread, so no problem.(Note: everything you’re doing is illegal. Never block the main thread, and never sleep.)
you are blocking with waiting the main thread for queue to finish the task. So updating label text code not running on main thread. That’s by its not updating.
Try with async method that will not block the main thread.