1 #import "HMViewController.h"2 3 @interfaceHmviewcontroller ()4@property (Weak, nonatomic) Iboutlet Uiimageview *ImageView;5 @end6 7 @implementationHmviewcontroller8 9- (void) ViewdidloadTen { One [Super Viewdidload]; A //additional setup after loading the view, typically from a nib. - } - the //Click download Picture Download picture is a time-consuming operation, put into a sub-thread to execute create a new thread to execute the download picture -- (void) Touchesbegan: (Nsset *) touches withevent: (Uievent *)Event - { - //Creating Threads + [Self performselectorinbackground: @selector (download) Withobject:nil]; - } + A /** at * Download Image - */ -- (void) Download - { - -NSLog (@"Download---%@", [Nsthread CurrentThread]); in - //1. URL of picture address to download toNSString *urlstr =@"http://d.hiphotos.baidu.com/image/pic/item/37d3d539b6003af3290eaf5d362ac65c1038b652.jpg"; + -Nsurl *url =[Nsurl Urlwithstring:urlstr]; the * //2. Download the binary data of the image according to the address (this code is the most time consuming) $NSLog (@"---begin");//Binary DataPanax NotoginsengNSData *data =[NSData Datawithcontentsofurl:url]; -NSLog (@"---End"); the + //3. Set up picture with binary data AUIImage *image =[UIImage Imagewithdata:data]; the + //Download the picture in the sub-thread, go back to the main thread to modify the UI interface, and involve the shuttle between the main thread and the child threads. - //4. Go back to the main thread and refresh the UI (for thread safety) just put the picture on it. $ [Self performselectoronmainthread: @selector (downloadfinished:) withobject:image Waituntildone:no]; $ //The following yes refers back to the main thread to set up the picture, the code is here to wait until the picture is set and then go down . - //no means to return to the main thread to set the picture, the code continues to execute, regardless of whether the picture is set. - the - //can give any line path things, the communication between the threads object is what you want to pass, that's what you want to set.Wuyi //[Self performselector: @selector (downloadfinished:) onthread:[nsthread Mainthread] Withobject:image Waituntildone:yes]; the - //and main thread communication, set UI interface picture Wu //[Self.imageview performselectoronmainthread: @selector (setimage:) withobject:image Waituntildone:yes]; - AboutNSLog (@"-----Done----"); $ } - - /** - * Set this image to be performed in the main thread A * + * @param image < #image description#> the */ -- (void) downloadfinished: (UIImage *) Image $ { theSelf.imageView.image =image; the theNSLog (@"downloadfinished---%@", [Nsthread CurrentThread]); the } - in @end
Network starts---multithreading---communication between threads (master) (v)