在后台线程,当需要更新UI时,需要使用async(execute:)函数POST到DispatchQueue.main,如下图所示:
static func executeInUIThread(_ uiThreadFunc: @escaping (Any?) -> Void, _ parms: Any?) {
DispatchQueue.main.async {
// Update UI
uiThreadFunc(parms)
}
}
可以访问闭合内部的uiThreadFunc
和parms
,因为closures capture variables from their 'surrounding context'.
但是,我不喜欢Swift风格(Swift中称为闭包)的编程.我如何才能做到这一点没有关闭?
我try 了以下几点:
static func executeInUIThread(_ uiThreadFunc: @escaping (Any?) -> Void, _ parms: Any?) {
let workItem = DispatchWorkItem(block: EventLoopMgr.InternalExecuteInUIThread)
DispatchQueue.main.async(execute: workItem)
}
private static func InternalExecuteInUIThread() {
// How to execute the uiThreadfunc? This block doesn't take any parameters.
}
它不工作是因为,初始化DispatchWorkItem时的block不带任何参数.因此,我不能通过uiThreadFunc
和parms
到这个街区.
我可以将uiThreadFunc
和parms
存储为静态变量,但需要使其成为多线程友好的.
有没有使用DispatchQueue.main而不使用闭包在UIThread中执行的更简单的方法?