ios开发-NSOperation介绍

简介:并发

一、NSOperation是苹果对GCD的一个面向对象的封装,是OC的异步

二、NSOperation同时提供了一些GCD不是特别容易实现的功能atom

三、将操做添加到队列,操做会被当即”异步“执行线程

四、NSOperation是个抽象的类,并不具有封装操做的能力,必须使用它的子类对象

   1>NSInvocationOperation继承

  2>NSBlockOperation队列

  3>自定义类继承NSOperation,实现内部的方法get

代码实现:it

示例1:NSInvocationOperationio

@interface TBViewController ()

@property(nonatomic,strong)NSOperation *myQueue;

@end

//懒加载

-(NSOperationQueue *)myQueue

{

  if(_myQueue == nil){

  _myQueue =[ [NSOperationQueue alloc]init];

}

  return _myQueue;

}

 

 

  -(void)touchesBegan:(NSSer *)touches withEvent:(UIEvent *)event

{

  [self opDemo1];

}

-(void)opDemo1

{

  //操做

  NSInvocationOperation *op =[ [NSInvocationOperation alloc]initWithTarget:self selector:@selector(downLoadImage) object:nil];

  //让操做启动,若是使用start方法,会在当前线程执行操做

 // [op start];

 

  //将操做添加到队列,操做会当即被“异步”执行

  [self.myQueue addOperation:op];

}

//下载图像

-(void)downLoadImage

{

  NSLog(@"下载图像:%@",[NSThread currentThread]);

}

 

示例2:NSBlockOperation

//NSOperationQueue  实例化的对象是并发队列

-(void)touchesBegan:(NSSer *)touches withEvent:(UIEvent *)event

{

  [self opDemo1];

}

-(void)opDemo2

{

  //操做

  for(int i = 0;i < 10; i ++)

{

  NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{

    NSLog(@"block ===%@",[NSThread currentThread]);

}];

  //添加到队列  经过运行能够看到是”并发“队列

  [self.myQueue addOperation:op];

}  

}

 

示例3:直接添加block

-(void)touchesBegan:(NSSer *)touches withEvent:(UIEvent *)event

{

  [self opDemo3];

}

-(void)opDemo3

{

   for(int i = 0; i < 10; i++)

{

  [self .myQueue addOperationWithBlock:^{

  NSLog(@"===== %@",[NSThread currentThread]);

}];

}

}

示例4:线程间的通信

-(void)touchesBegan:(NSSer *)touches withEvent:(UIEvent *)event

{

  [self opDemo4];

}

-(void)opDemo4

{

  [self.myQueue addOperationWithBlock:^{

  NSLog(@"下载图像:%@",[NSThread currentThread]);

  //下载完成须要更新UI,mainQueue  主队列

  [[NSOperationQueue mainQueue] addOperationWithBlock:^{

  NSLog(@"main %@",[NSThread currentThread]);

}];

}];

}

相关文章
相关标签/搜索