- (void)processImageDataWithBlock:(void (^)(NSData *imageData))processImage //声明函数processImageDataWithBlock 接收一个(void (^)(NSData *imageData))processImage 块参数, 该块参数接收一个NSData*参数。实质上这个块参数是异步回调函数 { NSString *url = self.imageURL; dispatch_queue_t callerQueue = dispatch_get_current_queue();//获取当前的主UI线程队列,所有对UI的操作都要针对UI线程队列进行 dispatch_queue_t downloadQueue = dispatch_queue_create("Photo Downloader", NULL);//创建一个异步线程队列 dispatch_async(downloadQueue, ^{ //异步执行下载图片任务 NSData *imageData = *insert code that fetches photo from server*; dispatch_async(callerQueue, ^{//下载数据线程返回后,通过传入的块数据更新UI processImage(imageData); }); }); dispatch_release(downloadQueue); }
//主UI调用更新UI- (void)viewWillAppear:(BOOL)animated { [spinner startAnimating]; [self.photo processImageDataWithBlock:^(NSData *imageData) {//此为回调函数定义 if (self.view.window) { UIImage *image = [UIImage imageWithData:imageData]; imageView.image = image; imageView.frame = CGRectMake(0, 0, image.size.width, image.size.height); scrollView.contentSize = image.size; [spinner stopAnimating]; } }]; }
时间: 2024-10-14 03:20:21