swift5主线程延迟操作的几种写法
swift写法
@objc func delayExecution(){
debugPrint("delayExecution")
}
func test1(){
self.perform(#selector(delayExecution), with: nil, afterDelay: 3)
NSObject.cancelPreviousPerformRequests(withTarget: self)
Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(delayExecution), userInfo: nil, repeats: false)
Thread.sleep(forTimeInterval: 3)
self.delayExecution()
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
self.delayExecution()
}
DispatchQueue.global().asyncAfter(deadline: .now() + 3) {
self.delayExecution()
}
}
oc写法:
- (void)viewDidLoad {
[super viewDidLoad];
[self performSelector:@selector(delayExecution) withObject:nil afterDelay:3];
[NSObject cancelPreviousPerformRequestsWithTarget:self];
[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(delayExecution) userInfo:nil repeats:NO];
[NSThread sleepForTimeInterval:3];
[self delayExecution];
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");
}
|