线程的常用基本属性 (异步下载图片)
name : 程序员调试的时候可以使用
优先级 :优先级高的线程不一定比优先级低的线程先执行,完全靠CPU 的算法来
�线程的生命周期
- 新建
- 就绪
- 运行
- 阻塞
- 死亡
实例:
怎么让子线程的图片到主线程来更新界面?
异步下载图片
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) UIImageView *testImageView;
@property (weak, nonatomic) UIScrollView *scrollView;
@end
@implementation ViewController
//重写此方法,默认不会加载xib&sb
-(void)loadView{
UIScrollView *sc = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
self.scrollView = sc;
self.view = sc;
UIImageView *imageView = [[UIImageView alloc] init];
self.testImageView = imageView;
[self.view addSubview: self.testImageView];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// [self downloadIMG];
//创建线程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(downloadIMG) object:nil];
[thread start];
}
//下载图片
-(void)downloadIMG{
NSLog(@"downloadimg %@",[NSThread currentThread]);
//网络卡
// [NSThread sleepForTimeInterval:3];
NSString*imgAddr=@"http://jiangsu.china.com.cn/uploadfile/2014/0329/20140329102034577.jpg";
NSURL *url = [NSURL URLWithString:imgAddr];
//获取到图片的原始数据
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
//线程间通信 子->主
//参数1:方法
//参数2:方法的参数
//参数3:等待执行完成
[self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:NO];
}
//更新UI
-(void)updateUI:(UIImage *)image{
NSLog(@"updateUI %@",[NSThread currentThread]);
self.testImageView.image = image;
//根据图片的大小来调整位置
[self.testImageView sizeToFit];
[self.scrollView setContentSize:image.size];
}
@end