iOS開發小功能之十一:線程間的通訊(3種方式),ios3種
三種方法都是通過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)download314 {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 *)image32 {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,然後設定自動布!!