IOS延時

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關(guān)聯(lián)全部延時方法
    + (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget;
    // 調(diào)用
    [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>

    // 執(zhí)行,不等待計時器,立即執(zhí)行延遲操作
    - (void)fire;
    
    // 銷毀/徹底取消計時器
    - (void)invalidate;
    
    // 暫停/恢復(fù)
    @property (copy) NSDate *fireDate;
    // 暫停,其實是把啟動時間延遲到
    [timer setFireDate:[NSDate distantFuture]];
    // 恢復(fù)
    [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>結(jié)果</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>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容