IOS延时

1. performSelector(NSObject)方法

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

** 取消**

    // 取消指定方法
    + (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;

2.1.1 使用

    // 执行,不等待计时器,立即执行延迟操作
    - (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」新增
+ (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));

2.2.1 使用

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

2.2.2 结果

    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];

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

参考资料

  • 浅谈iOS开发中方法延迟执行的几种方式
  • iOS 延迟执行方法
  • NSTimer知识点和倒计时的实现

你可能感兴趣的:(IOS延时)