三大常用法寶
本文章著重介紹多線程的基本用法妆艘,本文件的例子是下載圖片為例子殷蛇,子線程下載圖片谱轨,主線程更新圖片
經(jīng)典案例
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
子線程下載任務(wù)
dispatch_async(dispatch_get_main_queue(), ^{
主線程更新UI
});
});
NSThread
//動(dòng)態(tài)創(chuàng)建線程
-(void)dynamicCreateThread{
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(loadImageSource:) object:imgUrl];
thread.threadPriority = 1;// 設(shè)置線程的優(yōu)先級(0.0 - 1.0,1.0最高級)
[thread start];
}
//靜態(tài)創(chuàng)建線程
-(void)staticCreateThread{
[NSThread detachNewThreadSelector:@selector(loadImageSource:) toTarget:self withObject:imgUrl];
}
//隱式創(chuàng)建線程
-(void)implicitCreateThread{
[self performSelectorInBackground:@selector(loadImageSource:) withObject:imgUrl];
}
-(void)loadImageSource:(NSString *)url{
NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
UIImage *image = [UIImage imageWithData:imgData];
if (imgData!=nil) {
[self performSelectorOnMainThread:@selector(refreshImageView:) withObject:image waitUntilDone:YES];
}else{
NSLog(@"there no image data");
}
}
-(void)refreshImageView:(UIImage *)image{
[self.loadingLb setHidden:YES];
[self.imageView setImage:image];
}
NSOperation & NSOperationQueue
//使用子類NSInvocationOperation
-(void)useInvocationOperation{
NSInvocationOperation *invocationOperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(loadImageSource:) object:imgUrl];
//[invocationOperation start];//直接會(huì)在當(dāng)前線程主線程執(zhí)行
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[queue addOperation:invocationOperation];
}
//使用子類NSBlockOperation
-(void)useBlockOperation{
NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{
[self loadImageSource:imgUrl];
}];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[queue addOperation:blockOperation];
}
//使用繼承NSOperation
-(void)useSubclassOperation{
LoadImageOperation *imageOperation = [LoadImageOperation new];
imageOperation.loadDelegate = self;
imageOperation.imgUrl = imgUrl;
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[queue addOperation:imageOperation];
}
-(void)loadImageSource:(NSString *)url{
NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
UIImage *image = [UIImage imageWithData:imgData];
if (imgData!=nil) {
[self performSelectorOnMainThread:@selector(refreshImageView1:) withObject:image waitUntilDone:YES];
}else{
NSLog(@"there no image data");
}
}
-(void)refreshImageView1:(UIImage *)image{
[self.loadingLb setHidden:YES];
[self.imageView setImage:image];
}