iOS 中 3 种常见的定时器

作者: angelen | 来源:发表于2016-06-23 22:52 被阅读218次

    很多时候我们会想在多少秒以后执行一个任务(方法),比如说 2s 后隐藏 ProgressHUD 什么的,就可以使用定时器

    //
    //  ViewController.m
    //  160623_小知识
    //
    //  Created by angelen on 16/6/23.
    //  Copyright © 2016年 ANGELEN. All rights reserved.
    //
    
    #import "ViewController.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        
        // 常见的 3 种定时器
        
        // 第 1 种:performSelector
        NSLog(@"1111");
        // 3.0s 以后 执行showNSLog: 方法,如果 withObject 不为 nil,则是传递过去的参数
        // 注意,这个方法不会影响后面代码的执行,所以打印顺序是 1111, 2222, look
        [self performSelector:@selector(showNSLog) withObject:nil afterDelay:3.0];
        NSLog(@"2222");
        
        // 第 2 种:GCD
        NSLog(@"3333");
        // 这个是 GCD,执行顺序和上面一样
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // code to be executed after a specified delay
            NSLog(@"ok");
        });
        NSLog(@"4444");
        
        // 第 3 种:NSTimer
        // 如果 repeats 为 YES,那么就是没隔 3.0s 就重复一次 showNSLog 这个方法
        [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(showNSLog) userInfo:nil repeats:NO];
    }
    
    - (void)showNSLog {
        NSLog(@"look");
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    @end
    

    开发常用,记录一下🌚

    相关文章

      网友评论

        本文标题:iOS 中 3 种常见的定时器

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