-
原理分析
ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)invocationOperation:(id)sender {
//创建invocation的对像
NSInvocationOperation *invocation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(inBackground) object:nil];
//需要手动开启
[invocation start];
}
-(void)inBackground
{
NSLog(@"current = %@ main = %@",[NSThread currentThread],[NSThread mainThread]);
}
- (IBAction)blockOperation:(id)sender {
NSBlockOperation *blockOper = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"current = %@ \n main = %@",[NSThread currentThread],[NSThread mainThread]);
}];
[blockOper start];
}
- (IBAction)operationQueue:(id)sender {
//创建队列对象:
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
NSInvocationOperation *invocation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(inBackground) object:nil];
NSBlockOperation *block = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"current = %@ \n main = %@",[NSThread currentThread],[NSThread mainThread]);
}];
//将子类对象添加到队列
[queue addOperation:invocation];
[queue addOperation:block];
// [self performSelectorOnMainThread:<#(nonnull SEL)#> withObject:nil waitUntilDone:YES];
//回到主线程的内容
NSBlockOperation *onMain = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"current = %@ \n main = %@",[NSThread currentThread],[NSThread mainThread]);
}];
[[NSOperationQueue mainQueue]addOperation:onMain];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
-
NSOperation实现添加图片
#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.
}
@end