一、Runloop
无输入的sources 或 timers事件源,那么runloop会立即退出。
![](https://img.haomeiwen.com/i787331/0b1e1a52516d62cd.png)
image.png
一、PerformSelector延迟事件
perform(<#T##aSelector: Selector##Selector#>, with: <#T##Any?#>, afterDelay: <#T##TimeInterval#>)
作用向当前Runloop添加一个timer事件源
1.1、在子线程执行未开启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)");
}
![](https://img.haomeiwen.com/i787331/4e98ffe6ba4fa1d5.png)
image.png
1.2、在子线程执行开启runloop 结果: 执行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时,已经有timer事件源,所以runloop不会因为无任何事件源而退出
RunLoop.current.run()
print("touchesBegan3")
}
print("touchesBegan4")
}
![](https://img.haomeiwen.com/i787331/79878aca7e60d2e9.png)
image.png
![](https://img.haomeiwen.com/i787331/c11ab77325d0d586.png)
image.png
1.3、在子线程执行开启runloop 结果:执行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")
}
![](https://img.haomeiwen.com/i787331/40a2fabbfc50bb92.png)
image.png
![](https://img.haomeiwen.com/i787331/d9b99b4115f217ce.png)
image.png
1.4、取消PerformSelector延迟事件
@objc func onCancelPerformAction() {
/** 1.单独取消perform的执行事件*/
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(onPerformAction), object: nil)
/** 2.取消perform的所有执行事件*/
NSObject.cancelPreviousPerformRequests(withTarget: self)
}
网友评论