目前,我正在尝试将后台线程简化为我的应用程序中的主线程执行。
我这样做的方式是:
import Foundation
infix operator ~> {}
private let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
func ~> (backgroundClosure: () -> (), mainClosure: () -> ()) {
dispatch_async(queue) {
backgroundClosure()
dispatch_async(dispatch_get_main_queue(), mainClosure)
}
}
这会让我做类似的事情:
{ println("executed in background thread") } ~> { println("executed in main thread") }
现在......我想扩展这个功能,以便能够dispatch_after
到主线程,所以也许我希望它在0.25秒之后调用或者什么。
有没有办法通过以某种方式传递参数来实现这一目标?
理想情况下,我能够实现类似backgroundClosure ~>(0.25) mainClosure
的内容,但我怀疑这是可能的
答案 0 :(得分:2)
只是一个建议:
infix operator ~> {}
private let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
func ~> (backgroundClosure: () -> (), secondParam: (delayTime:Double, mainClosure: () -> () )) {
// you can use the `delayTime` here
dispatch_async(queue) {
backgroundClosure()
dispatch_async(dispatch_get_main_queue(), secondParam.mainClosure)
}
}
使用方法:
{ print("executed in background thread") } ~> (0.25, { print("executed in main thread") })
答案 1 :(得分:0)
试试这个:
private let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)
infix operator ~>{ associativity left precedence 140}
func ~> (backgroundClosure: ()->() , mainClosure: ()->()) {
dispatch_async(queue) { () -> Void in
backgroundClosure()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
mainClosure()
})
}}