- (void)viewDidLoad {
[super viewDidLoad];
// [self layout];
UIButton *but=[[UIButton alloc]initWithFrame:CGRectMake(50, 500, 275, 30)];
[but setTitle:@"下一页" forState:UIControlStateNormal];
[but addTarget:self action:@selector(jump) forControlEvents:UIControlEventTouchUpInside];
[but setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[but setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
[self.view addSubview:but];
}
-(void)jump{
ThreadViewController *con=[[ThreadViewController alloc]init];
[self presentViewController:con animated:NO completion:nil];
}
-(void)layout{
_image=[[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
_image.contentMode=UIViewContentModeScaleAspectFit;//图片居中
[self.view addSubview:_image];
UIButton *but=[[UIButton alloc]initWithFrame:CGRectMake(50, 500, 275, 30)];
[but setTitle:@"下载" forState:UIControlStateNormal];
[but addTarget:self action:@selector(loadImage) forControlEvents:UIControlEventTouchUpInside];
[but setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[but setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
[self.view addSubview:but];
}
//非多线程
//-(void)loadImage{
// NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:@""]];
// UIImage *imaged=[UIImage imageWithData:data];
// _image.image=imaged;
//}
#pragma mark
//多线程(使用线程添加图片)
-(void)loadImage{
// NSThread *thread=[[NSThread alloc]initWithTarget:self selector:@selector(myThread) object:nil];
// [thread start];//执行线程 (启动线程,并不代表立即执行。而是出于一种就绪状态,当系统调用时才真正执行)
//方法2 :使用类方法
[NSThread detachNewThreadSelector:@selector(myThread) toTarget:self withObject:nil];
}
#pragma mark 子线程中的操作
-(void)myThread{
NSLog(@"===进线程了===");
NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://scimg.jb51.net/allimg/160815/103-160Q509544OC.jpg"]];
// UIImage *imaged=[UIImage imageWithData:data];
// _image.image=imaged;
//这个方法是NSObject的分类方法,每个NSObject对象都有这个方法
[self performSelectorOnMainThread:@selector(mainThreadHandle:) withObject:data waitUntilDone:YES];
}
#pragma mark 回归主线程的一个更新UI的方法
-(void)mainThreadHandle:(NSData *)data{
UIImage *imaged=[UIImage imageWithData:data];
_image.image=imaged;
}