05-线程间通讯

线程间通讯


  • 从网络中下载一张图片放入到UIImageView中
- (void)touchBegin:(NSSet *)touches withEvent:(UIEvent *)event
{
	//1.下载图片
	/*
	//测试执行时间
	//NSDate *begin = [NSDate date];
	CFAbsoluteTime begin = CFAbsoluterTimeGetCurrent();
	
	//从网络下载一张图片
	NSURL *url = [NSURL URLWihtString:@"图片资源网址"];
	NSData *data = [NSData dataWithContentsOfURL:url];//耗时,应开启子线程
	
	//NSDate *end = [NSDate date];
	//NSLog(@"%f",[end timeIntervalSincedate:begin]);
	CFAbsoluteTime end = CFAbsoluteTimeGetCurrent();
	NSLog(@"%f",end - begin);
	
	//2.将二进制转换为图片
	UIImage *image = [UIImage imageWithData:data];
	//3.显示图片
	self.imageView.image = image;
	*/
	
	//开启一个子线程,下载图片
	[self performSelectorInBackground:@selector(download) withObject:nil];
}
  • 在主线程中下载图片会影响性能,应该开启一个子线程
- (void)download
{
	//1.下载图片
	NSURL *url = [NSURL URLWihtString:@"图片资源网址"];
	NSData *data = [NSData dataWithContentsOfURL:url];//耗时,应开启子线程
	
	//2.将二进制转换为图片
	UIImage *image = [UIImage imageWithData:data];
	
	//3.更新UI
#warning 注意:千万不要再子线程中更新UI,会出问题
	//self.imageView.image = image;//不能子子线程中更新UI
	//在主线程中更新UI
	[self performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];//开发中常用
	
	//[self performSelectorOnMainThread:@selector(updateImage:) withObject:image waitUntilDone:YES];
	
	NSLog(@"------");
}

- (void)updateImage:(UIImage *)image
{
	NSLog(@"++++++++");
	self.imageView.image = image;
}
  • waitUntilDone:
    • 如果传入YES,那么会等待@selector中的函数执行完毕,就可以执行之后的代码
    • 如果传入NO,那么不会等待@selector中的函数执行完毕,就可以执行之后的代码
更新UI的方法
  • 1.使用setImage:(开发中常用)
 [self performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];
  • 2.使用自定义函数:(了解)
 [self performSelectorOnMainThread:@selector(updateImage:) withObject:image waitUntilDone:YES];
 
 - (void)updateImage:(UIImage *)image
{
	self.imageView.image = image;
}
  • 3.使用:performSelector:(了解)
    • 可以在指定的线程中,调用指定对象的指定方法
 [self performSelector:@selector(updateImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];
 
- (void)updateImage:(UIImage *)image
{
	self.imageView.image = image;
}
posted @ 2015-09-03 16:15  紫之灵玲  阅读(103)  评论(0编辑  收藏  举报