GCDを使用して非UI関連非同期タスクObject-C非同期マルチスレッドロードネットワークピクチャを処理

6353 ワード

2つのコアメソッド:dispatch_asyncとdispatch_async_fは,Block Objects法とC Functions法にそれぞれ対応する.シーンを挙げてみましょう.
ネットワークから画像をダウンロードする必要がある場合は、このダウンロード作業を非同期スレッドに捨てることができます.そして、画像のダウンロードが完了したら、メインスレッドに渡して、メインスレッドにこの画像を表示させます.このようなシーンでは、甬道非同期タスクが必要です.ここでは前述の__についても触れたblock方式でローカルリソースを操作します.
コードのデモは次のとおりです.
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(concurrentQueue, ^{
    __block UIImage *image = nil;
    dispatch_sync(concurrentQueue, ^{ 
        /* Download the image here */
    });
    dispatch_sync(dispatch_get_main_queue(), ^{
        /* Show the image to the user here on the main queue*/
    }); 
}); 

 
 
具体的なコード実装を見てみましょう.
- (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, ^{ 
            /* Download the image here */
            /* iPad's image from Apple's website. Wrap it into two lines as the URL is too long to fit into one line */
            NSString *urlAsString = @"http://images.apple.com/mobileme/features"\ "/images/ipad_findyouripad_20100518.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){
                image = [UIImage imageWithData:imageData]; /* We have the image. We can use it now */
            }
            else if (downloadError != nil){
                NSLog(@"Error happened = %@", downloadError); 
            } 
            else 
            {
                NSLog(@"No data could get downloaded from the URL."); 
            }
        });

        dispatch_sync(dispatch_get_main_queue(), ^{
            /* Show the image to the user here on the main queue*/
            if (image != nil){
                /* Create the image view here */
                UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
                /* Set the image */ 
                [imageView setImage:image];
                /* Make sure the image is not scaled incorrectly */ 
                [imageView setContentMode:UIViewContentModeScaleAspectFit];
                /* Add the image to this view controller's view */ 
                [self.view addSubview:imageView];
            } else {
                NSLog(@"Image isn't downloaded. Nothing to display.");
            } 
        });
    }); 
}