iOS 中 3 种常见的定时器

很多时候我们会想在多少秒以后执行一个任务(方法),比如说 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

开发常用,记录一下🌚

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,533评论 25 709
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,294评论 4 61
  • 夫妻不和导致肾系统病 近年有很多调查表明,有百分之九十多的离婚夫妇,离婚的原因是性生活不协调,或男方阳痿、早泄、前...
    妙语文献阅读 571评论 0 1
  • 在爱与被爱的过程中,我们都曾经历过痛苦、恐惧,也体验过狂喜与极乐,我们渴望建立真挚的亲密关系,却又害怕再度受伤。 ...
    Doris66666阅读 736评论 0 0
  • 双层奶油蛋糕 狮子王 蓝白色 上面插一个插牌 放一些狮子王的装饰 500 翻糖饼干立体的两块 20*2=40 ...
    Angel翻糖蛋糕阅读 270评论 0 0