异步下载图片
开辟线程 去执行另外一个任务 执行完毕 主线程里面的需要的数据 的再次更新 每一个线程都是独立的代码片片段 当主线程触发下载任务 开辟另一个线程的时候 主线程会继续执行 子线程也会独立执行
使用alloc init 必须手动启动线程
NSThread *thread = [[NSThread alloc]initWithTarget:selfselector:@selector(downLoadOperation) object:nil];
thread.name = @"下载图片线程";
[thread start];
或者使用 [NSThread detachNewThreadSelector:@selector(downLoadOperation) toTarget:self withObject:nil];
具体代码如下
#import "ViewController.h"
@interface ViewController ()
{
UIImageView *imageView ;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor grayColor];
imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
imageView.layer.cornerRadius = 50;
imageView.layer.masksToBounds = YES;
imageView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:imageView];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changePoint:)];
[self.view addGestureRecognizer:tap];
UIButton *button = [UIButton buttonWithType:0];
button.frame = CGRectMake(0, 20, 100, 30);
[button setTitle:@"下载图片" forState:UIControlStateNormal];
[button addTarget:self action:@selector(downLoadImage:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (BOOL)prefersStatusBarHidden
{
return YES;
}
- (void)changePoint:(UITapGestureRecognizer *)sender
{
获取当前线程[NSThread currentThread]
NSLog(@"点击线程:%@",[NSThread currentThread]);
imageView.center = [sender locationInView:self.view];
}
- (void)downLoadImage:(UIButton *)sender
{
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(downLoadOperation) object:nil];
thread.name = @"下载图片线程";
[thread start];
}
- (void)downLoadOperation
{
NSLog(@"下载线程:%@",[NSThread currentThread]);
模拟 下载的耗时任务的操作
sleep(3);
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://img.xgo-img.com.cn/pics/1505/1504430.jpg"]];
当操作完毕之后刷新ui 在主线程里面去刷新
从子线程回到主线程去刷新页面
[self performSelectorOnMainThread:@selector(updataUI:) withObject:data waitUntilDone:YES];
}
- (void)updataUI:(NSData *)datas
{
NSLog(@"刷新线程:%@",[NSThread currentThread]);
imageView.image = [UIImage imageWithData:datas];
}
@end