swift多線程
使用@MainActor能自動(dòng)將 func 切換到主線程更新UI,而不用管外部調(diào)用到底是在子線程中調(diào)用曹货,還是在主線程中調(diào)用,惫撰。一個(gè)async方法,方法內(nèi)部寫了更新 UI操作揪阿,在該方法前加了@MainActor后,哪怕在子線程中調(diào)用該async方法也不會(huì) crash咆畏。
@MainActor func showAndDismissSuccessDialog() async {
await showSuccessDialog()
try? await Task.sleep(nanoseconds: 1000000000)
await dismissSuccessDialog()
}
@MainActor 只能對(duì)async/await的代碼生效
@MainActor 不會(huì)對(duì)Callback中的代碼生效南捂,例如:
@MainActor class ListViewModel: ObservableObject {
func load() {
loader.loadItems { [weak self] result in
self?.result = result
}
}
}
如果想讓@MainActor 對(duì)Callback生效,我們需要用withCheckedContinuation將我們的異步callback代碼旧找,轉(zhuǎn)換成async/await模式溺健, 例如:
@MainActor func dismissProgressDialog() async {
await withCheckedContinuation { continuation in
dismissProgressDialogSuspending {
continuation.resume(returning: ())
}
}
}
參考:
https://hicc.pro/p/swift/the-main-actor-attribute
https://zhuanlan.zhihu.com/p/395147531
https://www.hackingwithswift.com/articles/233/whats-new-in-swift-5-5