您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

iOS 多線程詳解:Grand Central Dispatch 的用法與實踐

編輯:iOS 相關教學

Grand Central Dispatch(GCD)是異步執行任務的技術之一,它以隊列為核心抽象,讓開發者不必直接操作線程。

三種類型的 dispatch queue

1)主隊列 Main queue,運行在主線程上,通過 dispatch_get_main_queue 獲取。

/*!
 * @function dispatch_get_main_queue
 *
 * @abstract
 * Returns the default queue that is bound to the main thread.
 *
 * @discussion
 * In order to invoke blocks submitted to the main queue, the application must
 * call dispatch_main(), NSApplicationMain(), or use a CFRunLoop on the main
 * thread.
 *
 * @result
 * Returns the main queue. This queue is created automatically on behalf of
 * the main thread before main() is called.
 */
__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0)
DISPATCH_EXPORT struct dispatch_queue_s _dispatch_main_q;

#define dispatch_get_main_queue() \
    DISPATCH_GLOBAL_OBJECT(dispatch_queue_t, _dispatch_main_q)

從聲明中不難看出,dispatch_get_main_queue 本身也是一個 dispatch_queue_t。

2)並行隊列 global dispatch queue,通過 dispatch_get_global_queue 獲取,系統提供多個不同優先級的全局隊列。並行隊列中任務的開始順序與加入順序一致,但完成順序不保證。

3)串行隊列 serial queues,通常用於按順序同步訪問,可以創建任意數量,各串行隊列之間彼此並發。

當你希望任務按某個特定順序執行時,串行隊列非常有用:它在同一時刻只執行一個任務。我們還可以用串行隊列代替鎖來保護共享數據——和鎖不同的是,串行隊列能保證任務在一個可預知的順序下執行。

串行隊列通過 dispatch_queue_create 創建,可以用 dispatch_retain 和 dispatch_release 增減引用計數(在 ARC 環境下通常不再需要手動調用)。

GCD 的常見用法

// 後台執行
dispatch_async(dispatch_get_global_queue(0, 0), ^{
    // something
});

// 主線程執行
dispatch_async(dispatch_get_main_queue(), ^{
    // something
});

// 一次性執行
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    // code to be executed once
});

// 延遲 2 秒執行
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){
    // code to be executed on the main queue after delay
});

// 自定義 dispatch_queue_t
dispatch_queue_t urls_queue = dispatch_queue_create("blog.devtang.com", NULL);
dispatch_async(urls_queue, ^{
    // your code
});
dispatch_release(urls_queue);

// 合併匯總結果
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
    // 並行執行的線程一
});
dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
    // 並行執行的線程二
});
dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
    // 匯總結果
});

一個完整的 GCD 示例

異步下載數據,完成後回到主線程刷新:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSURL * url = [NSURL URLWithString:@"https://www.baidu.com"];
    NSError * error;
    NSString * data = [NSString stringWithContentsOfURL:url
                                              encoding:NSUTF8StringEncoding
                                                 error:&error];
    if (data != nil) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"call back, the data is: %@", data);
        });
    } else {
        NSLog(@"error when download:%@", error);
    }
});

讓 App 在後台多活一會兒

GCD 的另一個用處,是讓程序在後台運行得更久。

未使用 GCD 時,App 被按下 Home 鍵退出後,最多只有 5 秒鐘做保存或清理資源的工作。而借助 GCD 配合後台任務 API,App 最多可以有約 10 分鐘在後台持續運行,這段時間可以用來清理本地緩存、上報統計數據等。

// AppDelegate.h 文件
@property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundUpdateTask;

// AppDelegate.m 文件
- (void)applicationDidEnterBackground:(UIApplication *)application {
    [self beingBackgroundUpdateTask];
    // 在這裡加上你需要長久運行的代碼
    [self endBackgroundUpdateTask];
}

- (void)beingBackgroundUpdateTask {
    self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [self endBackgroundUpdateTask];
    }];
}

- (void)endBackgroundUpdateTask {
    [[UIApplication sharedApplication] endBackgroundTask:self.backgroundUpdateTask];
    self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}

以上就是 GCD 在 iOS 中的核心用法介紹,希望對大家有所幫助。

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