swift中延遲執行

// 1.perform(必須在主線程中執行)
self.perform(#selector(delayExecution), with: nil, afterDelay: 3)
// 取消
NSObject.cancelPreviousPerformRequests(withTarget: self)

// 2.timer(必須在主線程中執行)
Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(delayExecution), userInfo: nil, repeats: false)

// 3.Thread (在主線程會卡主界面)
Thread.sleep(forTimeInterval: 3)
self.delayExecution()

// 4.GCD 主線程/子線程
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
    self.delayExecution()
}

DispatchQueue.global().asyncAfter(deadline: .now() + 3) {
    self.delayExecution()
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章