線程的常用基本屬性 (異步下載圖片)
name : 程序員調(diào)試的時(shí)候可以使用
優(yōu)先級(jí) :優(yōu)先級(jí)高的線程不一定比優(yōu)先級(jí)低的線程先執(zhí)行,完全靠CPU 的算法來(lái)
?線程的生命周期
- 新建
- 就緒
- 運(yùn)行
- 阻塞
- 死亡
實(shí)例:
怎么讓子線程的圖片到主線程來(lái)更新界面?
異步下載圖片
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) UIImageView *testImageView;
@property (weak, nonatomic) UIScrollView *scrollView;
@end
@implementation ViewController
//重寫(xiě)此方法,默認(rèn)不會(huì)加載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];
//創(chuàng)建線程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(downloadIMG) object:nil];
[thread start];
}
//下載圖片
-(void)downloadIMG{
NSLog(@"downloadimg %@",[NSThread currentThread]);
//網(wǎng)絡(luò)卡
// [NSThread sleepForTimeInterval:3];
NSString*imgAddr=@"http://jiangsu.china.com.cn/uploadfile/2014/0329/20140329102034577.jpg";
NSURL *url = [NSURL URLWithString:imgAddr];
//獲取到圖片的原始數(shù)據(jù)
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
//線程間通信 子->主
//參數(shù)1:方法
//參數(shù)2:方法的參數(shù)
//參數(shù)3:等待執(zhí)行完成
[self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:NO];
}
//更新UI
-(void)updateUI:(UIImage *)image{
NSLog(@"updateUI %@",[NSThread currentThread]);
self.testImageView.image = image;
//根據(jù)圖片的大小來(lái)調(diào)整位置
[self.testImageView sizeToFit];
[self.scrollView setContentSize:image.size];
}
@end