-
原理分析
ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//打印当前线程
NSLog(@"current = %@",[NSThread currentThread]);
//获取主线程
NSLog(@"%@",[NSThread mainThread]);
//判断当前是否为主线程
NSLog(@"%d",[NSThread isMainThread]);
#pragma mark --- 手动开启子线程
//1.创建线程对象
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(sayHi) object:nil];
//.线程休眠
// [NSThread sleepForTimeInterval:5];
//开启线程
[thread start];
//结束当前线程
// [thread cancel];
//退出当前线程
// [NSThread exit];
#pragma mark --- 自动开启子线程;
[NSThread detachNewThreadSelector:@selector(sayHi) toTarget:self withObject:nil];
}
-(void)sayHi
{
@autoreleasepool {
NSLog(@"current = %@ %@ %d",[NSThread currentThread],[NSThread mainThread],[NSThread isMainThread]);
}
//回到主线程修改当前背景颜色
//回到主线程方法
//是否等待子线程完成之后进入主线程
[self performSelectorOnMainThread:@selector(changeColor) withObject:nil waitUntilDone:YES];
}
-(void)changeColor
{
self.view.backgroundColor = [UIColor cyanColor];
NSLog(@"current = %@ main = %@",[NSThread currentThread],[NSThread mainThread]);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
-
NSThread实现添加图片
#import "ViewController.h"
@interface ViewController ()
@property(nonatomic,strong)UIImageView* imageView;
@property(nonatomic,strong)NSData* imageData;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.imageView = [[UIImageView alloc]initWithFrame:([UIScreen mainScreen].bounds)];
[self.view addSubview:self.imageView];
}
#pragma mark --- 创建子线程加载数据
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self performSelectorInBackground:@selector(loadImage) withObject:nil];
}
-(void)loadImage
{
NSString *path = @"http://img4.imgtn.bdimg.com/it/u=2730485761,138060261&fm=26&gp=0.jpg";
NSURL *url = [NSURL URLWithString:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
self.imageData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//进入主线程,刷新 UI
[self performSelectorOnMainThread:@selector(reloadImage) withObject:nil waitUntilDone:YES];
}
-(void)reloadImage
{
NSLog(@"%@ \n %d",[NSThread currentThread],[NSThread isMainThread]);
//imageView数据源展示
self.imageView.image = [UIImage imageWithData:self.imageData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}