您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發基礎

iOS 三種計時器實戰對比:NSTimer、CADisplayLink 與 GCD Timer

編輯:iOS 開發基礎

iOS 開發裡的「計時」需求無所不在,但工具選錯往往會踩坑。以下把三種主流方案的使用方式與特性一次講清楚。

一、NSTimer

寫法一,便利構造器:

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                  target:self
                                                selector:@selector(action:)
                                                userInfo:nil
                                                 repeats:NO];
[timer invalidate];

呼叫上述方法後,target 的計數會 +1,任務執行完畢才會 -1。如果是重複執行的計時器,必須手動關閉,否則對應的釋放方法永遠不會被呼叫。

寫法二(推薦),先建立再手動加入 RunLoop:

NSTimer *timer = [NSTimer timerWithTimeInterval:5
                                         target:self
                                       selector:@selector(timerAction)
                                       userInfo:nil
                                        repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
[timer invalidate];

要注意的延遲問題:無論是一次性還是週期性計時器,實際觸發時間都與它加入的 RunLoop 及 RunLoop Mode 有關。如果該 RunLoop 正在執行一段連續運算(例如滑動列表),計時器就會被延後觸發。

二、CADisplayLink

- (void)startDisplayLink {
    self.displayLink = [CADisplayLink displayLinkWithTarget:self
                                                  selector:@selector(handleDisplayLink:)];
    [self.displayLink addToRunLoop:[NSRunLoop currentRunLoop]
                            forMode:NSDefaultRunLoopMode];
}

- (void)handleDisplayLink:(CADisplayLink *)displayLink {
    // 每幀執行
}

- (void)stopDisplayLink {
    [self.displayLink invalidate];
    self.displayLink = nil;
}

CADisplayLink 是一個能讓你以「螢幕刷新率同步」的頻率把內容畫到螢幕上的計時器類別。以特定模式註冊到 RunLoop 之後,每當螢幕完成一次內容刷新,RunLoop 就會向 CADisplayLink 指定的 target 發送一次 selector 訊息。

由於 iOS 裝置的螢幕刷新率是固定的,CADisplayLink 正常情況下每次刷新結束都會被呼叫,精度相當高。它的使用場景相對專一,特別適合需要持續重繪的 UI 場景,例如自訂動畫引擎或影片播放的渲染迴圈——因為它本身就與螢幕刷新同步,你不需要另外去關心刷新頻率。

三、GCD Timer

執行一次:

double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    // 執行你的事件
});

重複執行:

NSTimeInterval period = 1.0; // 設定時間間隔

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), period * NSEC_PER_SEC, 0); // 每秒觸發

dispatch_source_set_event_handler(_timer, ^{
    // 在這裡執行事件
});

dispatch_resume(_timer);

關鍵差異在於:NSTimer 受 RunLoop 影響,而 GCD 計時器不受影響——畢竟 RunLoop 本身也是建立在 GCD 之上的。這也是為什麼 GCD Timer 更適合做不受主執行緒阻塞影響的後台計時。


實戰範例:一個會「補償」的倒數計時器

App 進入背景後 NSTimer 會停止,回到前台時如果直接繼續倒數,時間就會對不上。解法是記錄進入背景的時間點,回前台時把差值補回來。

@interface ViewController ()

@property (nonatomic, strong) NSTimer *timer;   // 計時器
@property (nonatomic, assign) int countDown;    // 倒數值
@property (nonatomic, strong) NSDate *beforeDate; // 上次進入背景的時間

@end

static int const tick = 60;

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNotification];
    [self startCountDown];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                   name:UIApplicationDidEnterBackgroundNotification
                                                 object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                   name:UIApplicationWillEnterForegroundNotification
                                                 object:nil];
    [self stopTimer];
}

- (void)setupNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                            selector:@selector(enterBG)
                                                name:UIApplicationDidEnterBackgroundNotification
                                              object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                            selector:@selector(enterFG)
                                                name:UIApplicationWillEnterForegroundNotification
                                              object:nil];
}

/** 進入背景,記錄當前時間 */
- (void)enterBG {
    _beforeDate = [NSDate date];
}

/** 回到前台,依停留時長補償倒數值 */
- (void)enterFG {
    NSDate *now = [NSDate date];
    int interval = (int)ceil([now timeIntervalSinceDate:_beforeDate]);
    int val = _countDown - interval;

    if (val > 1) {
        _countDown -= interval;
    } else {
        _countDown = 1;
    }
}

/** 開始倒計時 */
- (void)startCountDown {
    _countDown = tick; // 重置計時

    _timer = [NSTimer timerWithTimeInterval:1.0
                                     target:self
                                   selector:@selector(timerFired:)
                                   userInfo:nil
                                    repeats:YES];

    // 使用 NSRunLoopCommonModes,才能保證 RunLoop 切換模式時計時器仍正常運作
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    // 注意:計時器存活期間,self 是被強引用的
}

- (void)timerFired:(NSTimer *)timer {
    if (_countDown == 0) {
        [self stopTimer];
        NSLog(@"重新發送");
    } else {
        _countDown -= 1;
        NSLog(@"倒計時中:%d", _countDown);
    }
}

- (void)stopTimer {
    if (_timer) {
        [_timer invalidate];
    }
}

@end

三種方案的定位可以這樣記:NSTimer 簡單直覺但受 RunLoop 拖累;CADisplayLink 精度最高、天生對齊螢幕刷新;GCD Timer 精度好且不受 RunLoop 干擾,適合後台計時。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved