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

iOS 中的 Run Loop 淺析:從 while 迴圈到 Mode 模型

編輯:iOS 開發綜合

Run Loop 是與線程緊密相關的重要概念,但日常開發中直接用到它的場合不多,多數講解又急著堆結論,反而讓人摸不著頭緒。本文用「逐步進化代碼」的方式,從一個 while 迴圈出發,把 Run Loop 的結構、NSRunLoop 的角色以及 Mode 模型一個個推導出來。

一、Run Loop 到底是什麼

線程執行完就會被銷毀。若想讓線程一直存活,最直接的做法是在裡面寫個迴圈:

- (void)myThread:(id)sender {
    while (TRUE) {
        @autoreleasepool {
            // do some jobs
            // break in some condition
            usleep(10000);
        }
    }
}

現在線程能一直跑了。新需求出現:在這個線程運行期間,還要能從其他線程動態往裡面添加或移除任務。這正是 NSRunLoop 厲害的地方。簡單進化一下:

NSMutableArray *targetQueue;
NSMutableArray *actionQueue;

- (void)myThread:(id)sender {
    while (TRUE) {
        @autoreleasepool {
            // do some jobs
            // break in some condition

            NSUInteger targetCount = [targetQueue count];
            for (NSUInteger index = 0; index < targetCount; ++index) {
                id  target = targetQueue[index];
                SEL action = NSSelectorFromString(actionQueue[index]);
                if ([target respondsToSelector:action]) {
                    [target performSelector:action withObject:nil];
                }
            }
            usleep(10000);
        }
    }
}

這樣一來,其他線程只要同時往 targetQueue 與 actionQueue 加入對象和方法,這個線程就能執行動態添加的代碼了。

所以所謂 run loop,本質上就是這個結構:

while (TRUE) {
    // break in some condition
}

注意:這個結構和 NSRunLoop 這個類名字很像,但完全不是同一樣東西。那 NSRunLoop 又是什麼?它是把上面這套「任務隊列 + 執行邏輯」封裝起來的類。我們自己寫一個簡化版:

@interface MyNSTimer : NSObject {
    id target;
    SEL action;
    float interval;
    CFAbsoluteTime lasttime;
}
- (void)invoke;
@end

@implementation MyNSTimer
- (void)invoke {
    if ([target respondsToSelector:action]) {
        [target performSelector:action withObject:nil];
    }
}
@end


@interface MyNSRunloop : NSObject {
    NSMutableArray *timerQueue;
}
- (void)addTimer:(MyNSTimer *)t;
- (void)executeOnce;
@end

@implementation MyNSRunloop
- (void)addTimer:(MyNSTimer *)t {
    @synchronized(timerQueue) {
        [timerQueue addObject:t];
    }
}
- (void)executeOnce {
    CFAbsoluteTime currentTime = CFAbsoluteTimeGetCurrent();
    @synchronized(timerQueue) {
        for (MyNSTimer *t in timerQueue) {
            if (currentTime - t.lasttime > t.interval) {
                t.lasttime = currentTime;
                [t invoke];
            }
        }
    }
}
@end


@interface MyNSThread : NSObject {
    MyNSRunloop *runloop;
}
- (void)main:(id)sender;
@end

@implementation MyNSThread
- (void)main:(id)sender {
    while (TRUE) {
        @autoreleasepool {
            // do some jobs
            // break in some condition
            [runloop executeOnce];
            usleep(10000);
        }
    }
}
@end

到這裡,Run Loop 的結構就算抽象出來了。給 MyNSThread 的一個實例添加任務,它內部的 MyNSRunloop 對象會負責管理:

MyNSTimer *timer1 = [MyNSTimer scheduledTimerWithTimeInterval:1
                                                       target:obj1
                                                     selector:@selector(download1:)];
[myThread1.runloop addTimer:timer1];

MyNSTimer *timer2 = [MyNSTimer scheduledTimerWithTimeInterval:2
                                                       target:obj2
                                                     selector:@selector(download2:)];
[myThread1.runloop addTimer:timer2];

二、Mode 模型:為什麼滑動時 NSTimer 不觸發

iOS 極重視用戶體驗。UITableView 滑動之所以順暢,是因為界面更新都在主線程完成。但奇怪的是,即使往主線程添加再多 NSTimer 定時任務,也不會影響列表滑動。主線程是怎麼做到的?答案就在 run loop 的 mode。

再改進一次代碼,把任務隊列從 RunLoop 中剝離出來:

@interface MyNSRunloopMode : NSObject {
    NSMutableArray *_timerQueue;
    NSString *_name;
}
- (void)addTimer:(MyNSTimer *)timer;
- (void)executeOnce;
@end


@interface MyNSRunloop : NSObject {
    NSMutableSet *_modes;
    MyNSRunloopMode *_currentMode;
}
- (void)addTimer:(MyNSTimer *)t;
- (void)addTimer:(MyNSTimer *)t forMode:(NSString *)mode;
- (void)executeOnce;
@end


@implementation MyNSRunloopMode
- (void)executeOnce {
    CFAbsoluteTime currentTime = CFAbsoluteTimeGetCurrent();
    @synchronized(timerQueue) {
        for (MyNSTimer *t in timerQueue) {
            if (currentTime - t.lasttime > t.interval) {
                t.lasttime = currentTime;
                [t invoke];
            }
        }
    }
}
@end


@implementation MyNSRunloop
- (void)addTimer:(MyNSTimer *)timer {
    [self addTimer:timer forMode:NSDefaultRunLoopMode];
}

- (void)addTimer:(MyNSTimer *)timer forMode:(NSString *)modeName {
    MyNSRunloopMode *mode = nil;
    for (mode in _modes) {
        if ([mode.name isEqualToString:modeName]) break;
    }
    [mode addTimer:timer];
}

- (void)executeOnce {
    [_currentMode executeOnce];
}
@end

我們多了一個 MyNSRunloopMode 類,原本掛在 RunLoop 上的執行任務改掛到 mode 對象裡。而 RunLoop 持有一個 mode 集合與一個 currentMode。Run Loop 在任一時刻只運行在 currentMode 之下,也就只會執行該 mode 裡的任務。可以這樣指定當前 mode:

[NSRunLoop runMode:beforeDate:]

系統預先定義了若干 mode,每個都有自己的名字,其中最常用的是 NSDefaultRunLoopMode。添加任務時指定相應的 mode 名稱,任務就會被放進對應的 mode。

現在謎底揭曉:NSTimer 預設被加到 NSDefaultRunLoopMode,而 UITableView 滑動時主線程並不在這個 mode 下(而是切換到 NSEventTrackingRunLoopMode),所以 NSTimer 的任務壓根不會被執行,自然不影響滑動。滑動結束後,主線程切回 NSDefaultRunLoopMode,定時任務又恢復執行。當然,也可以主動把 timer 加到任何 mode:

[NSRunLoop addTimer:forMode:]

實務上最常見的應用就是這個:把 timer 同時加入多個 mode,讓它在滑動期間也照常觸發。

[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

本文只談了 Run Loop 的基本原理,真實實現自然複雜得多,但萬變不離其宗。有興趣的話,不妨往下研究它的源碼實現。

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