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>