编程知识点

IOS延时

2017-05-07  本文已影响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>

上一篇 下一篇

猜你喜欢

热点阅读