在 iOS 開發中,延時執行常用於等待動畫、延遲彈窗或模擬非同步流程。常見方式包括 GCD、NSTimer、performSelector 與 NSThread。
使用 dispatch_after 可以在指定時間後執行區塊,也可指定佇列。它屬於非阻塞方式,適合在背景或主執行緒安排延遲工作。
double delay = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delay * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^{
NSLog(@"GCD 延時執行");
});
NSTimer 適合用於重複或單次計時。使用 scheduledTimerWithTimeInterval 建立後,通常會加入目前的 run loop。若要取消,可呼叫 invalidate。
[NSTimer scheduledTimerWithTimeInterval:8.0 target:self selector:@selector(delayMethod2) userInfo:nil repeats:NO];
performSelector:withObject:afterDelay: 可在延遲後呼叫指定方法,寫法簡短,適合物件內部的延遲呼叫。
[self performSelector:@selector(delayMethod) withObject:nil afterDelay:5.0];
NSThread 的 sleepForTimeInterval 會讓目前執行緒暫停指定時間。這種方式較直接,但若放在主執行緒,可能造成畫面卡住,因此需謹慎使用。
[NSThread sleepForTimeInterval:11.0];
選擇延時方式時,應考慮是否需要取消、是否會阻塞執行緒,以及要在哪個佇列執行。