#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self opDemo6];
}
// 子线程下载完,回到主线程
- (void)opDemo6 {
[[[NSOperationQueue alloc]init]addOperationWithBlock:^{
NSLog(@"下载文件A %@",[NSThread currentThread]);
// 回到主线程
[[NSOperationQueue mainQueue]addOperationWithBlock:^{
NSLog(@"回到主线程刷新的UI%@",[NSThread currentThread]);
}];
}];
}
- (void)opDemo5 {
// 如果我们不需要操作队列,返回值对我们没用的时候,就可以使用此方法来添加操作到队列
[[[NSOperationQueue alloc]init]addOperationWithBlock:^{
NSLog(@"%@",[NSThread currentThread]);
}];
}
- (void)opDemo4 {
// 创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
// 添加操作到队列
[queue addOperationWithBlock:^{
NSLog(@"%@",[NSThread currentThread]);
}];
}
- (void)opDemo3 {
// 创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
for (int i = 0; i < 200; ++i) {
// 创建操作
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"%@--%d",[NSThread currentThread],i);
}];
// 把操作添加到队列
[queue addOperation:op];
}
}
// 效果跟GCD的全局队列一样
- (void)opDemo2 {
// 创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
for (int i = 0; i < 200; ++i) {
// 创建操作
NSInvocationOperation *op = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(demo:) object:@(i)];
// 把操作添加到队列
[queue addOperation:op];
}
}
// NSBlockOperation
- (void)opDemo1 {
// 创建操作
NSBlockOperation *block = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"%@",[NSThread currentThread]);
}];
// 创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
// 把操作添加到队列
[queue addOperation:block];
}
// NSInvocationOperation
- (void)opDemo {
// 创建一个操作
NSInvocationOperation *op = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(demo:) object:@"hello"];
// 开始 -- 没有开启线程,在当前线程执行此操作
// [op start];
// 创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
// 把操作添加到队列 -- 添加到队列之后,会开启线程(异步执行)
[queue addOperation:op];
NSLog(@"end");
}
- (void)demo:(id)value {
NSLog(@"%@ - %@",[NSThread currentThread],value);
}
@end