今天讓我們來看一看ios線程中是怎麼樣通信的。
#import "ViewController.h"
@interface ViewController ()
{
UIImageView *_image;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
CGRect frame = [[UIScreen mainScreen]bounds];
_image = [[UIImageView alloc]init];
_image.frame =CGRectMake(0, 0, frame.size.width,frame.size.height-300);
[self.view addSubview:_image];
}
//當用戶觸摸屏幕的時候,開啓一個線程,下載圖片
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self performSelectorInBackground:@selector(downloadImage) withObject:nil];
}
//子線程的任務,負責下載網絡中的圖片資源
-(void)downloadImage
{
// 1. 構造圖片資源的url
NSURL *url = [NSURL URLWithString:@"http://c.hiphotos.baidu.com/image/pic/item/e61190ef76c6a7ef2469025dfefaaf51f3de667a.jpg"];
//2.下載圖片
NSData *data = [NSData dataWithContentsOfURL:url];
//3.將二進制data轉換成圖片對象
UIImage *image = [UIImage imageWithData:data];
//在ios開發中,更新UI的操作必須放倒主線程中執行
[_image performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];
}
//把下載到的圖片給UIImageView
-(void)setImage:(UIImage *)image
{ _image.image = image;
}
@end
這就是線程中的通信的方式,當用戶觸摸這個屏幕的時候,就開啓一個線程去執行下載任務,下載完成,取到主線程把下載好的圖片給UIImageView.