今天让我们来看一看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.
原文地址:http://blog.csdn.net/wq820203420/article/details/45014169