两个核心方法:dispatch_async和dispatch_async_f,分别对应Block Objects方法和C Functions方法。 当我们需要从网络下载一个图片,可以将这个下载工作丢到一个异步线程里面,然后当图片下载完毕后,我们再交给主线程,让主线程去显示这个图片。在这种场景下,我们就需要甬道异步任务了。这里也涉及到了之前提到的__block方式操作本地资源。 代码演示如下: 01. dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ); 02. dispatch_async(concurrentQueue, ^{ 03. __block UIImage *image = nil; 04. dispatch_sync(concurrentQueue, ^{ 05. /* Download the image here */ 06. }); 07. dispatch_sync(dispatch_get_main_queue(), ^{ 08. /* Show the image to the user here on the main queue*/ 09. }); 10. }); 下面看一个具体的代码实现: 01. - ( void ) viewDidAppear:(BOOL)paramAnimated{ 02. dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ); 03. dispatch_async(concurrentQueue, ^{ 04. __block UIImage *image = nil; 05. dispatch_sync(concurrentQueue, ^{ 06. /* Download the image here */ 07. /* iPad's image from Apple's website. Wrap it into two lines as the URL is too long to fit into one line */ 08. NSString *urlAsString = @ "http://images.apple.com/mobileme/features" \ "/images/ipad_findyouripad_20100518.jpg" ; 09. NSURL *url = [NSURL URLWithString:urlAsString]; 10. NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url]; 11. NSError *downloadError = nil; 12. NSData *imageData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:&downloadError]; 13. if (downloadError == nil && imageData != nil){ 14. image = [UIImage imageWithData:imageData]; /* We have the image. We can use it now */ 15. } 16. else if (downloadError != nil){ 17. NSLog(@ "Error happened = %@" , downloadError); 18. } 19. else 20. { 21. NSLog(@ "No data could get downloaded from the URL." ); 22. } 23. }); 24. 25. dispatch_sync(dispatch_get_main_queue(), ^{ 26. /* Show the image to the user here on the main queue*/ 27. if (image != nil){ 28. /* Create the image view here */ 29. UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds]; 30. /* Set the image */ 31. [imageView setImage:image]; 32. /* Make sure the image is not scaled incorrectly */ 33. [imageView setContentMode:UIViewContentModeScaleAspectFit]; 34. /* Add the image to this view controller's view */ 35. [self.view addSubview:imageView]; 36. } else { 37. NSLog(@ "Image isn't downloaded. Nothing to display." ); 38. } 39. }); 40. }); 41. } |
|