前言:关于线程和进程,其实不难理解,进程就相当于手机中的视频播放器,线程就相当于在视频播放器中观看视频,多线程相当于观看视频的同时,也下载视频。
/*
-
加载一张图片
-
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]);
}
网友评论