//
// ViewController.m
// NSThread
//
// Created by dc008 on 15/12/24.
// Copyright © 2015年 崔晓宇. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
{ //用于显示下载的图片
UIImageView *_imageView;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self layout];
}
- (void)layout{
_imageView = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
_imageView.contentMode = UIViewContentModeScaleAspectFill;
[self.view addSubview:_imageView];
//下载按钮
UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(120, 420, 80, 20)];
[button setTitle:@"加载图片" forState:UIControlStateNormal];
[button addTarget:self action:@selector(loadImageWithMultiThread) forControlEvents:UIControlEventTouchUpInside];
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
[self.view addSubview:button];
}
- (void)noNSThread{
//在资源下载加载的过程中,由于网络原因,有时候我们是很难保证下载时间的,如果不使用多线程可能用户完成一个下载操作需要很长时间的等待,而且在这个过程中无法进行其他操作-》阻塞。
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://img2.3lian.com/2014/f7/5/d/22.jpg"]]];
_imageView.image = image;
}
#pragma mark 多线程下载图片
- (void)loadImageWithMultiThread{
//方法1:使用对象方法
//创建一个线程
NSThread *thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(loadImage) object:nil];
[thread1 start];//启动一个线程,并不代表立即执行,而是处于就绪状态,当系统调度时才真正执行
//方法2.使用类方法
// [NSThread detachNewThreadSelector:@selector(loadImage) toTarget:self withObject:nil];
}
- (void)loadImage{
//请求图片数据
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://img2.3lian.com/2014/f7/5/d/22.jpg"]];
//注意只能在主线程中更新UI
//performSelectorOnMainThread 这个方法是NSObject的分类方法,每个NSObject对象都有这个方法
[self performSelectorOnMainThread:@selector(updataImageView:) withObject:data waitUntilDone:YES];
}
- (void)updataImageView : (NSData *)imageData{
UIImage *image = [UIImage imageWithData:imageData];
_imageView.image = image;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end