IOS延时

作者: 半白乀 | 来源:发表于2017-05-07 11:51 被阅读0次

1. performSelector(NSObject)方法

    [self performSelector:(nonnull SEL) withObject:(nullable id) afterDelay:(NSTimeInterval)];

** <small>取消</small>**

    // 取消指定方法
    + (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget selector:(SEL)aSelector object:(nullable id)anArgument;
    // 取消Target关联全部延时方法
    + (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget;
    // 调用
    [NSObject cancelPreviousPerformRequestsWithTarget:self];

2. NSTimer方法

2.1
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;

<small>2.1.1 <small>使用</small></small>

    // 执行,不等待计时器,立即执行延迟操作
    - (void)fire;
    
    // 销毁/彻底取消计时器
    - (void)invalidate;
    
    // 暂停/恢复
    @property (copy) NSDate *fireDate;
    // 暂停,其实是把启动时间延迟到
    [timer setFireDate:[NSDate distantFuture]];
    // 恢复
    [timer setFireDate:[NSDate date]]; or
    [timer setFireDate:[NSDate distantPast]];        

2.2 「10.0」<small>新增</small>
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));

<small>2.2.1 <small>使用</small></small>

WLog(@"NSTimer Start!");
[NSTimer scheduledTimerWithTimeInterval:2 repeats:NO block:^(NSTimer * _Nonnull timer) {
    WLog(@"2 seconds later!");
}];
WLog(@"Next Step!");

<small>2.2.2 <small>结果</small></small>

    2017-05-07 10:55:22.328 THEWEATHER[34802:5552585] NSTimer Start!
    2017-05-07 10:55:22.328 THEWEATHER[34802:5552585] Next Step!
    2017-05-07 10:55:24.329 THEWEATHER[34802:5552585] 2 seconds later!

3. GCD

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(int64_t)(delayInSeconds * NSEC_PER_SEC)),
    dispatch_get_main_queue(), ^{
       // code to be executed after a specified delay
    });

4. sleep(NSThread)方法

    + (void)sleepForTimeInterval:(NSTimeInterval)ti;
    // 使用
    [NSThread sleepForTimeInterval:3];

<small>* 各个方法特性参考其他资料,不对的地方还请指正!</small>

参考资料
<small>

相关文章

  • IOS3

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

  • IOS延时

    1. performSelector(NSObject)方法 ** 取消 ** 2. NSTimer方法 2....

  • iOS 延时

    1 NSTimer //1秒后执行 NSTimer *timer = [NSTimer timerWithTim...

  • iOS 延时执行的实现

    iOS中延时执行的4种方法

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

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

  • iOS延时请求

    需求 在某些时候,需要对请求进行延时处理。例如:对某条评论进行点赞,如果用户无限点击赞/取消赞按钮,就会无限发出请...

  • iOS 延时加载

  • iOS 延时加载

    这里列举了四种线程延时加载的方法, 1.performSelector方法 此方法必须在主线程中执行,并不是阻塞当...

  • iOS延时pop

    [weakSelf.navigationController performSelector:@selector(...

  • iOS中延时执行的几种方式的比较和汇总

    转载自:【转载】IOS中延时执行的几种方式的比较和汇总_leisurehuang34_新浪博客 本文列举了四种延时...

网友评论

    本文标题:IOS延时

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