Communication between iOS threads (GCD), iosgcd
1. Download an image from the network and display it on The view.
-(Void) imageDownload {dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {// network path NSURL * url = [NSURL URLWithString: @ "http://img.pconline.com.cn/images/photoblog/9/9/8/1/9981681/200910/11/1255259355826.jpg"]; // load the image NSData * data = [NSData dataWithContentsOfURL: url]; // generate the image UIImage * image = [UIImage imageWithData: data]; // return to the main thread dispatch_async (dispatch_get_main_queue (), ^ {self. imageView. image = image ;});});}
2. Download two images from the Internet. After both of them have been downloaded, they are combined into one image.
@ Interface ViewController () @ property (weak, nonatomic) IBOutlet UIImageView * imageView;/** image 1 */@ property (nonatomic, strong) UIImage * image1; /** Image 2 */@ property (nonatomic, strong) UIImage * image2; @ end
-(Void) group {dispatch_queue_t queue = dispatch_get_global_queue (queue, 0); // create a queue group dispatch_group_t group = dispatch_group_create (); // 1. download image 1 dispatch_group_async (group, queue, ^ {// network path of the image NSURL * url = [NSURL URLWithString: @ "http://img.pconline.com.cn/images/photoblog/9/9/8/1/9981681/200910/11/1255259355826.jpg"]; // load the image NSData * data = [NSData dataWithContentsOfURL: url]; // generate the image self. image1 = [UIImage imageWithData: data] ;}); // 2. download Image 2 dispatch_group_async (group, queue, ^ {// network path of the image NSURL * url = [NSURL URLWithString: @ "http://pic38.nipic.com/20140228/5571398_215900721128_2.jpg"]; // load the image NSData * data = [NSData dataWithContentsOfURL: url]; // generate the image self. image2 = [UIImage imageWithData: data] ;}); // 3. combine image 1 and Image 2 into a new image dispatch_group_notify (group, queue, ^ {// enable the new image context UIGraphicsBeginImageContext (CGSizeMake (100,100 )); // draw the image [self. image1 drawInRect: CGRectMake (0, 0, 50,100)]; [self. image2 drawInRect: CGRectMake (50, 0, 50,100)]; // obtain the image UIImage * image in the context = UIGraphicsGetImageFromCurrentImageContext (); // end context UIGraphicsEndImageContext (); // return to the main thread to display the image dispatch_async (dispatch_get_main_queue (), ^ {// 4. display the new image as self. imageView. image = image ;});});}