在專案開發中經常會用到方法的延時調用,具體的調用場景不做贅述,以下列舉現有的幾種實現方式:
方法一:performSelector (建議學習:phpstorm
[self performSelector:@selector(delayMethods) withObject:nil afterDelay:1.0];
#
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayMethods) object:nil];
[NSObject cancelPreviousPerformRequestsWithTarget:self];
可以主動取消操作:
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(delayMethods) userInfo:nil repeats:NO];
[timer invalidate];
方法二:NSTimer
[NSThread sleepForTimeInterval:1.0];
#取消延時操作:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [self delayMethods]; });
方法三:sleep
dispatch_queue_t queen = dispatch_get_global_queue(0, 0); dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), queen, ^{ [self delayMethods]; });
方法四:GCD
__weak typeof(self) ws = self; dispatch_queue_t queen = dispatch_get_global_queue(0, 0); dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queen); if (timer) { dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 1.0 * NSEC_PER_SEC); dispatch_source_set_event_handler(timer, ^{ [ws delayMethods]; }); dispatch_resume(timer); }
rrreee也可以設定是否重複執行:
rrreee註:
因為方法交給了GCD自動處理,因此不容易取消操作###以上是iOS幾種延遲執行方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!