前言:關于線程和進程,其實不難理解,進程就相當于手機中的視頻播放器,線程就相當于在視頻播放器中觀看視頻,多線程相當于觀看視頻的同時,也下載視頻。
/*
加載一張圖片
1、創建一個UIImageView,并放在父視圖上
2、創建一個子線程
3、通過url獲取網絡圖片
4、回到主線程
5、在主線程更新UI
*/
開辟線程的兩種方式:
1、手動開啟線程:
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(thread1:) object:@"thread1"];
[thread start];
2、自動開啟方式:
[NSThread detachNewThreadSelector:@selector(thread1:) toTarget:self withObject:@"thread1"];
獲取當前線程:
[NSThread currentThread];
線程的優先級:(0-1)默認是0.5
[NSThread setThreadPriority:1.0];
下面以加載一張網絡圖片為例具體介紹:
#import "ViewController.h"
#define kUrl @"http://store.storeimages.cdn-apple.com/8748/as-images.apple.com/is/image/AppleInc/aos/published/images/s/38/s38ga/rdgd/s38ga-rdgd-sel-201601?wid=848&hei=848&fmt=jpeg&qlt=80&op_sharpen=0&resMode=bicub&op_usm=0.5,0.5,0,0&iccEmbed=0&layer=comp&.v=1454777389943"
@interface ViewController ()
{
UIImageView *imageView;
UIImage *image;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor brownColor];
// 消除導航欄的影響
self.edgesForExtendedLayout = UIRectEdgeNone;
#pragma mark - ---NSThread開辟線程的兩種方式*****
/*
* 創建手動開啟方式
* 第三個參數:就是方法選擇器選擇方法的參數
*/
// NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(thread1:) object:@"thread1"];
// 開啟線程
//[thread start];
/*
*創建并自動開啟方式
*/
[NSThread detachNewThreadSelector:@selector(thread1:) toTarget:self withObject:@"thread1"];
NSLog(@"viewDidload方法所在的線程 %@",[NSThread currentThread]);
imageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 50, 200, 200)];
[self.view addSubview:imageView];
}
// 在子線程執行的方法
-(void)thread1:(NSString *)sender{
// [NSThread currentThread] 獲取到當前所在的信息
//NSThread *thread = [NSThread currentThread];
// thread.name = @"我是子線程";
// NSLog(@"thread1方法所在的線程%@",thread);
// [NSThread isMainThread]判斷當前線程是否是主線程
// BOOL ismainThread = [NSThread isMainThread];
// BOOL isMultiThread = [NSThread isMultiThreaded];
// setThreadPriority 設置線程的優先級(0-1)
//[NSThread setThreadPriority:1.0];
// sleepForTimeInterval 讓線程休眠
//[NSThread sleepForTimeInterval:2];
#pragma ----
// 從網絡加載圖片拼接并將它轉換為data類型的數據
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:kUrl]];
image = [UIImage imageWithData:data];
// waitUntilDone設為YES,意味著UI更新完才會去做其他操作
[self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];
}
-(void)updateUI:(UIImage *)kimage{
imageView.image = kimage;
NSLog(@"updateUI方法所在的線程%@",[NSThread currentThread]);
}