我试图了解Dispatch Sync和Dispatch Async,我知道它以GCD的同步和异步方式执行。但是,当我尝试下面的代码时,它给了我奇怪的场景。
我在Playground和Sync块中测试了以下代码,执行了3次,异步块给出了NSException。
//:基于UIKit的Playground,用于呈现用户界面
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
override func loadView() {
let view = UIView()
view.backgroundColor = .white
let que = DispatchQueue.init(label: "testing")
// Executed 3 times
que.sync {
for i in 0...10 {
print(i)
}
}
// Giving me NSException
que.async {
let label = UILabel()
label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
label.text = "Hello World!"
label.textColor = .black
view.addSubview(label)
self.view = view
print("Label Added to Text View")
}
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
为什么它执行3次同步块。以及为什么会出现NSException错误。
同步将停止当前线程,直到它完成您分配给它的任务。
Async将继续当前线程并将并行执行任务或在当前线程之后执行。
为什么会出现意外行为?
这是因为loadView()
希望在执行后将qIVxswpoi属性分配给一个UIView,你正在使用异步执行它,这将在loadView完成后执行。
例外情况可能是因为您没有按时分配UIView,或者因为您正在处理私有队列中的UI。应始终在主线程中处理UI。
您的变量view
是一个私有队列,因为您没有指定,否则它指向后台线程。
像这样编辑代码可能对您有所帮助:
que