美文网首页
iOS开发-延时执行

iOS开发-延时执行

作者: YYPan_ | 来源:发表于2018-05-30 11:11 被阅读0次

1.GCD

dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC);
dispatch_after(time, dispatch_get_main_queue(), ^{
    // 延时执行操作
});

注:dispatch_after方法本质是将任务延时添加到队列中,并不是延时执行任务,所以在对时间要求不是那么高的情况下也可以满足延时执行的要求。

2.performSelector

performSelector:<#(nonnull SEL)#> withObject:<#(nullable id)#> afterDelay:<#(NSTimeInterval)#> inModes:<#(nonnull NSArray<NSRunLoopMode> *)#>
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
label.backgroundColor = [UIColor redColor];
[self.view addSubview:label];

[label performSelector:@selector(setText:) withObject:@"延时2秒显示文字" afterDelay:2.0 inModes:@[NSRunLoopCommonModes]];

// 如果不使用系统的方法,也可以自定义方法
[self performSelector:@selector(showText) withObject:nil afterDelay:2.0 inModes:@[NSRunLoopCommonModes]];

注:mode使用NSRunLoopCommonModes的原因是当界面上有tableView、scrollView、textView等可滑动的view时,view滑动时延时执行函数不受影响。

3.NSTimer

/**
scheduledTimerWithTimeInterval创建的定时器会默认以NSDefaultRunLoopMode的方式自动添加到当前的runloop中
*/
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(delay) userInfo:nil repeats:NO];

/**
timerWithTimeInterval创建的定时器需要手动添加到runloop中
*/
NSTimer *timer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(delay) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

/**
不用时记得销毁
*/
[timer invalidate];
timer = nil;

注:如果界面上有tableView、scrollView、textView等可滑动的view,
当view滑动时,采用以上方式添加的定时器会停止,需要设置runloop的mode

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(delay) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

NSTimer *timer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(delay) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

相关文章

  • iOS开发-延时执行

    1.GCD 注:dispatch_after方法本质是将任务延时添加到队列中,并不是延时执行任务,所以在对时间要求...

  • 关于GCD常用的方法

    iOS开发多线程篇—GCD的常见用法 一、延迟执行 1.介绍 iOS常见的延时执行有2种方式 (1)...

  • iOS开发中常用的延时delay操作?区别?

    『导言』 在iOS开发中经常有需求,延时某个操作执行,比如启动页延时,来加载后台的数据,给人一种快的假象! 方法:...

  • iOS开发 GCD的延时执行

    GCD的延时执行需要使用@weakify 和@strongify来保留 不然会报错,并且没有断点 别问我是怎么知道...

  • 技术贴:3.iOS中的延时执行

    延迟执行也叫做延时执行。在iOS中有三种延时执行方式: 1.调用NSObject的方法 [self perform...

  • iOS 延时执行的实现

    iOS中延时执行的4种方法

  • IOS3

    1、 2、iOS中常用的延时方法iOS常见的延时执行有2种方式调用NSObject的方法[self perform...

  • IOS-延时执行

    IOS中延时执行的几种方式的比较和汇总 本文列举了四种延时执行某函数的方法及其一些区别。假如延时1秒时间执行下面的...

  • 多线程----GCD的常用函数和单例模式

    线程间的通信 从子线程回到主线程 延时执行 iOS常见的延时执行有两种方式p 调用NSObject的方法 p 使用...

  • iOS定时器,你真的会使用吗?

    前言 定时器的使用是软件开发基础技能,用于延时执行或重复执行某些方法。 我相信大部分人接触iOS的定时器都是从这段...

网友评论

      本文标题:iOS开发-延时执行

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