ios開發- NSOperation進階功能

來源:互聯網
上載者:User

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

直接上代碼

樣本1:

@interface TBViewController()

//隊列

@property(nonatomic,strong)NSOperationQueue *queue;

@end

//隊列的暫停和繼續(在storyboard中拖兩個按鈕,分別為暫停、繼續,連線)

//暫停

-(IBAction)pause

{

  if(self.queue.operationCount == 0){

  NSLog(@"無操作");

  return;

}

 

  //掛起》暫停  暫停是隊列,讓隊列暫時不再派發任務

  NSLog(@"暫停");

  [self.queue setSuspended:YES];  

}

//繼續

-(IBAction)resumue

{

  if(self.queue.operationCount == 0){

  NSLog(@"無操作");

  return;

}

  NSLog(@"繼續");

  [self.queue setSuspended:NO];

}

//懶載入

-(NSOperationQueue *)queue

{

  if(_queue == nil){

  _queue = [[NSOperationQueue alloc]init];

}

  return _queue;

}

 

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

{

  [self opDemo1];

}

//同時並發線程數量

-(void)opDemo1

{

  //線程開啟的隊列是由GCD底層決定的,程式員不能參與

 

/*

設定最大並發數的好處:線程開啟有消耗

3G:     2~3條線程,線程少,流量少,省錢,省電

WIFI:   5~6條線程,線程多,效率高,流量大,不花錢,可以隨時充電

*/

 

  self.queue maxConcurrentOperationCount = 3;//最大並發數量

  for(int i = 0;i < 100; i ++){

    [self.queue addOperationWithBlock:^{

      //阻塞

        [NSThread sleepForTimeInterval:2];

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

}];

}

}

 

樣本2:操作的依賴-》操作的執行順序

-(void)opDemo3

{

  /*

  例如:

  1、下載小電影的壓縮包

  2、解壓縮

  3、儲存檔案

  4、通知使用者

  */

NSBlockOperation*op1 = [NSBlockOperation blockOperationWithBlock:^{

    NSLog(@"下載:%@",[NSThread currentThread]);

}];

NSBlockOperation*op2 = [NSBlockOperation blockOperationWithBlock:^{

    NSLog(@"解壓縮:%@",[NSThread currentThread]);

}];

NSBlockOperation*op3 = [NSBlockOperation blockOperationWithBlock:^{

    NSLog(@"儲存:%@",[NSThread currentThread]);

}];

NSBlockOperation*op4 = [NSBlockOperation blockOperationWithBlock:^{

    NSLog(@"通知使用者:%@",[NSThread currentThread]);

}];

  //依賴

  [op2 addDependency:op1];

  [op3 addDependency:op3];

  [op4 addDependency:op3];

  //循環相依性(一定不要出現)

  [op1 addDependency:op4];

  

  //非同步  waitUntilFinished  等待所有操作完成在繼續

  [self.queue addOperations:@[op1,op2,op3] waitUntilFinished:NO];

//主隊列

  [[NSOperationQueue mainQueue] addOperation:op4];

}

 

總結:

/*

  NSOperation

1.是對GCD的封裝

2、是OC的,物件導向的,使用更加容易

3、提供了一些特殊的方法,是GCD不容易實現的,例如:最大並發線程數量、暫停和繼續

4、可以指定操作的依賴關係,依賴關係是可以跨隊列的

5、自訂的隊列,是並發隊列,操作是非同步任務

 

  GCD

1、是C語言的,難度有點大

2、once

3、after

4、GCD還有非常多複雜的功能

*/

 

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.