ios開發-NSOperation介紹

來源:互聯網
上載者:User

標籤:io   os   ar   使用   for   strong   sp   on   art   

簡介:

1、NSOperation是蘋果對GCD的一個物件導向的封裝,是OC的

2、NSOperation同時提供了一些GCD不是特別容易實現的功能

3、將操作添加到隊列,操作會被立即”非同步“執行

4、NSOperation是個抽象的類,並不具備封裝操作的能力,必須使用它的子類

   1>NSInvocationOperation

  2>NSBlockOperation

  3>自訂類繼承NSOperation,實現內部的方法

代碼實現:

樣本1:NSInvocationOperation

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

}];

}];

}

ios開發-NSOperation介紹

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.