开子线程下载图片,回到主线程刷新UI步骤

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[NSThread detachNewThreadSelector:@selector(download) toTarget:self withObject:nil];
} #pragma mark ----------------------
#pragma Methods //开子线程下载图片,回到主线程刷新UI
-(void)download
{
//1.确定URL
NSURL *url = [NSURL URLWithString:@"http://img4.duitang.com/uploads/blog/201310/18/20131018213446_smUw4.thumb.700_0.jpeg"]; //2.根据url下载图片二进制数据到本地
NSData *imageData = [NSData dataWithContentsOfURL:url]; //3.转换图片格式
UIImage *image = [UIImage imageWithData:imageData]; NSLog(@"download----%@",[NSThread currentThread]); //4.回到主线程显示UI
/*
第一个参数:回到主线程要调用哪个方法
第二个参数:前面方法需要传递的参数 此处就是image
第三个参数:是否等待
*/
//[self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:NO]; [self performSelector:@selector(showImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES]; // self.imageView.image = image;
NSLog(@"---end---");
} //更新UI操作
-(void)showImage:(UIImage *)image
{
self.imageView.image = image;
NSLog(@"UI----%@",[NSThread currentThread]);
}
performSelectorOnMainThread:和performSelector:方法都可以
也可以直接用对象self.imageView调用performSelectorOnMainThread:方法,使用对象self.imageView的image属性的setImage:方法来实现(这样可以省略创建showImage方法)。

[self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];

上一篇:WPF里面多线程访问UI线程、主线程的控件


下一篇:在非主线程中更新UI