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

iOS 開發(62):用 GCD 異步執行非 UI 任務

編輯:iOS 開發綜合

前言

GCD 真正的威力,要等到你把非 UI 的運算丟到主佇列以外的佇列上才看得見。UI 相關的操作必須留在主佇列,其餘的網路下載、檔案讀寫、大量資料處理,都應該異步執行以免卡住畫面。

兩個異步提交函式

dispatch_async:向分派佇列異步提交一個 Block。

dispatch_async(concurrentQueue, ^{ /* ... */ });

dispatch_async_f:向分派佇列異步提交一個 C 函式與上下文指標。

dispatch_async_f(concurrentQueue, NULL, printFrom1To1000);

實例一:背景下載圖片,主執行緒顯示

- (void) viewDidAppear:(BOOL)paramAnimated{
    // 建立全域並行佇列
    dispatch_queue_t concurrentQueue =
        dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    dispatch_async(concurrentQueue, ^{
        __block UIImage *image = nil;

        dispatch_sync(concurrentQueue, ^{
            /* 下載圖片 */
            NSString *urlAsString = @"https://up.2cto.com/2013/0519/20130519101223949.jpg";
            NSURL *url = [NSURL URLWithString:urlAsString];
            NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];

            NSError *downloadError = nil;
            NSData *imageData = [NSURLConnection
                                 sendSynchronousRequest:urlRequest
                                 returningResponse:nil
                                 error:&downloadError];

            if (downloadError == nil && imageData != nil){
                // 將 NSData 轉為圖片
                image = [UIImage imageWithData:imageData];
            }
            else if (downloadError != nil){
                NSLog(@"Error happened = %@", downloadError);
            }else{
                NSLog(@"No data could get downloaded from the URL.");
            }
        });

        // 回到主執行緒更新 UI
        dispatch_sync(dispatch_get_main_queue(), ^{
            if (image != nil){
                UIImageView *imageView = [[UIImageView alloc]
                                          initWithFrame:self.view.bounds];
                [imageView setImage:image];
                [imageView setContentMode:UIViewContentModeScaleAspectFit];
                [self.view addSubview:imageView];
            } else {
                NSLog(@"Image isn't downloaded. Nothing to display.");
            }
        });
    });
}

這個範例的重點是「分工」:下載在背景佇列、UI 更新切回主佇列。這樣的結構可以推廣到任何耗時任務。

實例二:背景產生資料檔並排序後顯示

@synthesize myLabel;

- (void)viewDidLoad
{
    [super viewDidLoad];

    dispatch_queue_t concurrentQueue =
        dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    /*
        若磁碟上還沒有這份隨機數檔案,就先產生並寫入
     */
    dispatch_async(concurrentQueue, ^{
        NSUInteger numberOfValuesRequired = 10000;

        if ([self hasFileAlreadyBeenCreated] == NO){
            dispatch_sync(concurrentQueue, ^{
                NSMutableArray *arrayOfRandomNumbers =
                    [[NSMutableArray alloc] initWithCapacity:numberOfValuesRequired];
                NSUInteger counter = 0;
                for (counter = 0; counter < numberOfValuesRequired; counter++){
                    unsigned int randomNumber = arc4random() % ((unsigned int)RAND_MAX + 1);
                    [arrayOfRandomNumbers addObject:
                        [NSNumber numberWithUnsignedInt:randomNumber]];
                }
                [arrayOfRandomNumbers writeToFile:[self fileLocation] atomically:YES];
            });
        }

        // 讀回檔案並升序排序
        __block NSMutableArray *randomNumbers = nil;
        dispatch_sync(concurrentQueue, ^{
            if ([self hasFileAlreadyBeenCreated]){
                randomNumbers = [[NSMutableArray alloc]
                                 initWithContentsOfFile:[self fileLocation]];
                [randomNumbers sortUsingComparator:^NSComparisonResult(id obj1, id obj2)
                {
                    NSNumber *number1 = (NSNumber *)obj1;
                    NSNumber *number2 = (NSNumber *)obj2;
                    return [number1 compare:number2];
                }];
            }
        });

        // 回到主執行緒刷新畫面
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([randomNumbers count] > 0){
                CGRect labelFrame = CGRectMake(0.0f, 0.0f, 300.0f, 200.0f);
                self.myLabel = [[UILabel alloc] initWithFrame:labelFrame];
                self.myLabel.numberOfLines = 10;
                self.myLabel.text = [[NSString alloc] initWithFormat:
                                     @"RandomNumbers is %@", randomNumbers];
                self.myLabel.font = [UIFont boldSystemFontOfSize:14.0f];
                self.myLabel.center = self.view.center;
                [self.view addSubview:self.myLabel];
            }
        });
    });
}

// 取得檔案路徑
-(NSString *)fileLocation{
    /*
        NSDocumentDirectory:文件目錄
        NSUserDomainMask:使用者主目錄
     */
    NSArray *folders = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                           NSUserDomainMask, YES);
    if ([folders count] == 0){ return nil; }

    NSString *documentsFolder = [folders objectAtIndex:0];
    return [documentsFolder stringByAppendingPathComponent:@"list.txt"];
}

// 判斷檔案是否已存在
- (BOOL) hasFileAlreadyBeenCreated{
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    return [fileManager fileExistsAtPath:[self fileLocation]];
}

三個值得記住的模式

  • 背景運算 → 主執行緒更新:任何 IO 或運算都丟到背景,UI 一律回主佇列,這是最基礎也最重要的分工。
  • __block 修飾跨 Block 的變數:Block 對外部變數是值捕獲,若要在 Block 之間傳遞結果(如範例中的 image、randomNumbers),必須加上 __block。
  • dispatch_sync 要慎用:同步等待會阻塞目前執行緒。在主佇列上對主佇列呼叫 dispatch_sync 會直接造成死鎖,正式專案中應優先考慮 dispatch_async 或 dispatch_group。

補充一點:範例中的 NSURLConnection sendSynchronousRequest: 僅為教學示意,真實專案請改用 NSURLSession 的異步 API,並把回呼切回主佇列處理 UI。

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