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]);

}];

}];

}

相關文章
相關標籤/搜索