三種方法都是通過touchesBegin監聽屏幕的觸摸實現
一、performSelector方式
1 #import "ViewController.h" 2 @interface ViewController () 3 @property (weak, nonatomic) IBOutlet UIImageView *imageView; 4 @end 5 @implementation ViewController 6 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 7 { 8 //放入子線程 9 [self performSelectorInBackground:@selector(download3) withObject:nil]; 10 } 11 12 //下載放入子線程,顯示圖片應該放在主線程!!!否則會導致刷新問題 13 - (void)download3 14 { 15 //圖片的網絡路徑 16 NSURL *url = [NSURL URLWithString:@"http://ww2.sinaimg.cn/mw690/63e6fd01jw1f3f3rf75goj20qo0zkagy.jpg"]; 17 //下載圖片數據 18 NSData *data = [NSData dataWithContentsOfURL:url]; 19 20 //生成圖片 21 UIImage *image = [UIImage imageWithData:data]; 22 //回到主線程顯示圖片方法一: 23 // [self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:YES]; 24 //回到主線程顯示圖片方法二: 25 //waitUntilDone:表示是否等待主線程做完事情后往下走,YES表示做完后執行下面事,NO表示跟下面事一起執行 26 [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES]; 27 //回到主線程顯示圖片方法三: 28 [self.imageView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES]; 29 } 30 //主線程顯示圖片 31 - (void)showImage:(UIImage *)image 32 { 33 self.imageView.image = image; 34 }
二、GCD方式
1 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 2 { 3 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 4 //圖片的網絡途徑 5 NSURL *url = [NSURL URLWithString:@"http://ww2.sinaimg.cn/mw1024/75614297jw1f34e5llyz4j20qo0zj0zl.jpg"]; 6 //加載圖片 7 NSData *data = [NSData dataWithContentsOfURL:url]; 8 //生成圖片 9 UIImage *image = [UIImage imageWithData:data];\ 10 //回到主線程 11 dispatch_async(dispatch_get_main_queue(), ^{ 12 self.imageView.image = image; 13 }); 14 }); 15 16 }
三、operation方式(此種方式更具有面向對象特性!)
1 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 2 { 3 //直接開始子線程執行任務 4 [[[NSOperationQueue alloc] init] addOperationWithBlock:^{ 5 NSURL *url = [NSURL URLWithString:@"http://ww4.sinaimg.cn/mw690/63e6fd01jw1ezxz499hy5j21gt0z94qq.jpg"]; 6 NSData *data = [NSData dataWithContentsOfURL:url]; 7 UIImage *image = [UIImage imageWithData:data]; 8 //回到主線程 9 [[NSOperationQueue mainQueue] addOperationWithBlock:^{ 10 //顯示圖片 11 self.imageView.image = image; 12 }]; 13 }]; 14 }
以上三種方式都需要在main storyboard中拖一個imageView,然后設置自動布!!
