一赦颇、Runloop
無輸入的sources 或 timers事件源啊鸭,那么runloop會立即退出蛇摸。
一急迂、PerformSelector延遲事件
perform(<#T##aSelector: Selector##Selector#>, with: <#T##Any?#>, afterDelay: <#T##TimeInterval#>)
作用向當前Runloop添加一個timer事件源
1.1影所、在子線程執(zhí)行未開啟runloop
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
print("touchesBegan1")
DispatchQueue.global().asyncAfter(deadline: .now() + 3) { [self] in
print("touchesBegan2")
self.perform(#selector(onPerformAction), with: nil, afterDelay: 1)
print("touchesBegan3")
}
print("touchesBegan4")
}
@objc func onPerformAction() {
print("onPerformAction:\(Thread.current)");
}
1.2、在子線程執(zhí)行開啟runloop 結(jié)果: 執(zhí)行onPerformAction成功
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
print("touchesBegan1")
DispatchQueue.global().asyncAfter(deadline: .now() + 3) { [self] in
print("touchesBegan2")
// 下面這行代碼等于向當前runloop添加timer事件源
self.perform(#selector(onPerformAction), with: nil, afterDelay: 1)
// 開啟runloop時僚碎,已經(jīng)有timer事件源猴娩,所以runloop不會因為無任何事件源而退出
RunLoop.current.run()
print("touchesBegan3")
}
print("touchesBegan4")
}
1.3、在子線程執(zhí)行開啟runloop 結(jié)果:執(zhí)行onPerformAction失敗
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
print("touchesBegan1")
DispatchQueue.global().asyncAfter(deadline: .now() + 3) { [self] in
print("touchesBegan2")
RunLoop.current.run()
self.perform(#selector(onPerformAction), with: nil, afterDelay: 1)
print("touchesBegan3")
}
print("touchesBegan4")
}
1.4、取消PerformSelector延遲事件
@objc func onCancelPerformAction() {
/** 1.單獨取消perform的執(zhí)行事件*/
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(onPerformAction), object: nil)
/** 2.取消perform的所有執(zhí)行事件*/
NSObject.cancelPreviousPerformRequests(withTarget: self)
}