IOS 15 主线程延迟的4种写法
@objc func delayExecution(){
debugPrint("delayExecution")
}
func test1(){
// 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()
}
}
oc写法:
- (void)viewDidLoad {
[super viewDidLoad];
// 1.perform(必须在主线程中执行)
[self performSelector:@selector(delayExecution) withObject:nil afterDelay:3];
// 取消
[NSObject cancelPreviousPerformRequestsWithTarget:self];
[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(delayExecution) userInfo:nil repeats:NO];
// 3.Thread (在主线程会卡主界面)
[NSThread sleepForTimeInterval:3];
[self delayExecution];
// 4.GCD 主线程/子线程
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self delayExecution];
});
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self delayExecution];
});
}
-(void)delayExecution{
NSLog(@"delayExecution");
}
网友评论