swift5主线程延迟 *** 作的几种写法

swift5主线程延迟 *** 作的几种写法,第1张

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");
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/993919.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存