swift5主线程延迟操作的几种写法
生活随笔
收集整理的這篇文章主要介紹了
swift5主线程延迟操作的几种写法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
swift5主線程延遲操作的幾種寫法
swift寫法
@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"); }總結
以上是生活随笔為你收集整理的swift5主线程延迟操作的几种写法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Coding For Fun 32小时:
- 下一篇: 新手开车13招技巧