注解:可以和gcd对比一下,NSOperation是实例化一个操作,然后将操作添加到队列中。而gcd则是,将一个block的任务添加到队列中,其实,原理是一样的。
NSOperation是个抽象类,并不具备封装操作的能力,必须使用它的子类
创建NSInvocationOperation对象
- (id)initWithTarget:(id)target selector:(SEL)sel object:(id)arg;
调用start方法开始执行操作
- (void)start;
一旦执行操作,就会调用target的sel方法
注意
默认情况下,调用了start方法后并不会开一条新线程去执行操作,而是在当前线程同步执行操作
只有将NSOperation放到一个NSOperationQueue中,才会异步执行操作
创建NSBlockOperation对象
+(id)blockOperationWithBlock:(void (^)(void))block;
- (void)addOperation:(NSOperation*)op;
-( void)addOperationWithBlock:( void (^)( void))block;
#import "ViewController.h"
@interfaceViewController ()
@property (nonatomic,strong) NSOperationQueue *myQueue;
@end
@implementation ViewController
/**
*NSOperationQueue实例化的队列是并发队列
*
*并发队列+异步操作
*/
- (NSOperationQueue *)myQueue
{
if (_myQueue ==nil)
{
_myQueue = [[NSOperationQueuealloc] init];
}
return_myQueue;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[selfopDemo4];
}
- (void)opDemo1
{
//操作
NSInvocationOperation *op = [[NSInvocationOperationalloc] initWithTarget:selfselector:@selector(downLoad)object:nil];
//将操作添加到队列,操作的downLoad方法会被异步执行
[self.myQueueaddOperation:op];
}
- (void)downLoad
{
NSLog(@"downLoad %@", [NSThreadcurrentThread]);
}
- (void)opDemo2
{
//创建操作--异步的
NSBlockOperation *op = [NSBlockOperationblockOperationWithBlock:^{
NSLog(@"NSBlockOperation %@", [NSThreadcurrentThread]);
}];
//将操作添加到队列(并发队列),操作中block内容将异步执行
[self.myQueueaddOperation:op];
}
//直接添加block==用到最多
- (void)opDemo3
{
//并发队列异步任务
[self.myQueueaddOperationWithBlock:^{
NSLog(@"addOperationWithBlock %@", [NSThreadcurrentThread]);
}];
}
/**
* 线程间的通信
*/
- (void)opDemo4
{
[self.myQueueaddOperationWithBlock:^{
NSLog(@"下载图像 %@", [NSThreadcurrentThread]);
//下载完成需要更新UI mainQueue主队列
[[NSOperationQueuemainQueue] addOperationWithBlock:^{
NSLog(@"%@", [NSThreadcurrentThread]);
}];
}];
}
@end