Today let's look at how the iOS thread communicates.
#import "ViewController.h"
@interface viewcontroller ()
{
uiimageview *_image;
}
@end
@implementation Viewcontroller
-(void) viewdidload {
[superviewdidload];
cgrect frame = [[uiscreen mainscreen] bounds ];
_image = [[uiimageviewalloc]init];
_image. Frame = CGRectMake (0,0, frame. ) size . width , frame. size . Height - - );
[self. View addsubview:_image];
}
// when the user touches the screen, open a thread, download the picture
-(void) Touchesbegan: ( Nsset *) touches withevent: (uievent *) Event
{
[self performselectorinbackground: @selector ( Downloadimage)withobject:nil];
}
// sub-thread tasks, responsible for downloading picture resources in the network
-(void) downloadimage
{
//1. constructs a picture resource URL
nsurl *url = [nsurlurlwithstring:@ "/http/ C.hiphotos.baidu.com/image/pic/item/e61190ef76c6a7ef2469025dfefaaf51f3de667a.jpg "];
//2. Download Image
nsdata *data = [nsdatadatawithcontentsofurl : url];
//3. the binary Data Convert to Picture object
UIImage *image = [UIImageimagewithdata:d ATA];
// in iOS development, The action to update the UI must be put down in the main thread to execute
[_imageperformselectoronmainthread:@selector( SetImage:)withobject: Image waituntildone:NO];
}
// give the downloaded image to Uiimageview
-(void) setimage: ( UIImage *) Image
{ _image. Image = image;
}
@end
This is the way of communication in the thread, when the user touches this screen, it opens a thread to perform the download task, the download completes, takes the main thread to download the good picture to Uiimageview.
IOSGCD Communication in a thread