美文网首页
iOS中几种延迟执行方法

iOS中几种延迟执行方法

作者: dequal | 来源:发表于2018-02-22 11:51 被阅读0次

    开发中经常会有延迟执行的要求,这里简单介绍几种常用的方法:

    1. performSelector方法
    2. Timer 定时器
    3. Thread 线程的sleep
    4. GCD
    

    Method1:performSelector

    [self performSelector:@selector(delayMethod) withObject:nil/*可传任意类型参数*/ afterDelay:2.0];
    

    注:此方法是一种非阻塞的执行方式,未找到取消执行的方法。

    Method2:NSTimer定时器

    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(delayMethod) userInfo:nil repeats:NO];
    

    注:此方法是一种非阻塞的执行方式,取消执行方法:- (void)invalidate;即可。

    Method3:NSThread线程的sleep

    [NSThread sleepForTimeInterval:2.0];
    

    注:此方法是一种阻塞执行方式,建议放在子线程中执行,否则会卡住界面。但有时还是需要阻塞执行,如进入欢迎界面需要沉睡3秒才进入主界面时。
    没有找到取消执行方式。

    Method4:GCD

    __block ViewController/*主控制器*/ *weakSelf = self;
    
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0/*延迟执行时间*/ * NSEC_PER_SEC));
    
    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        [weakSelf delayMethod];
    });
    

    注:此方法可以在参数中选择执行的线程,是一种非阻塞执行方式。没有找到取消执行方式。

    代码如下:

    //
    //  ViewController.m
    //  test-延迟执行的几种方法总结
    //
    //  Created by 邓昊 on 2018/2/22.
    //  Copyright © 2018年 邓昊. All rights reserved.
    //
    
    #import "ViewController.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        NSLog(@"---start---");
        [self method1PerformSelector];
    //    [self method2NSTimer];
    //    [self method3Sleep];
    //    [self method4GCD];
        NSLog(@"---next method---");
    
    }
    - (void)methodFiveAnimation{
        [UIView animateWithDuration:0 delay:2.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
        } completion:^(BOOL finished) {
            [self delayMethod];
        }];
    }
    - (void)method4GCD{
        __block ViewController *weakSelf = self;
        dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC));
        dispatch_after(delayTime, dispatch_get_main_queue(), ^{
            [weakSelf delayMethod];
        });
    }
    - (void)method3Sleep{
        [NSThread sleepForTimeInterval:2.0];
    }
    - (void)method2NSTimer{
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(delayMethod) userInfo:nil repeats:NO];
    }
    - (void)method1PerformSelector{
        [self performSelector:@selector(delayMethod) withObject:nil afterDelay:2.0];
    }
    - (void)delayMethod{
        NSLog(@"delayMethod");
    }
    
    @end
    
    

    相关文章

      网友评论

          本文标题:iOS中几种延迟执行方法

          本文链接:https://www.haomeiwen.com/subject/bjgatftx.html