iOS多線程編程之NSOperation和NSOperationQueue的使用(轉自容芳志專欄)

來源:互聯網
上載者:User

標籤:style   c   class   blog   code   java   

 轉自由http://blog.csdn.net/totogo2010/使用 NSOperation的方式有兩種,一種是用定義好的兩個子類:

NSInvocationOperation 和 NSBlockOperation。

另一種是繼承NSOperation

如果你也熟悉Java,NSOperation就和java.lang.Runnable介面很相似。和Java的Runnable一樣,NSOperation也是設計用來擴充的,只需繼承重寫NSOperation的一個方法main。相當與java 中Runnalbe的Run方法。然後把NSOperation子類的對象放入NSOperationQueue隊列中,該隊列就會啟動並開始處理它。

 

NSInvocationOperation例子:

 

和前面一篇博文一樣,我們實現一個下載圖片的例子。建立一個Single View app,拖放一個ImageView控制項到xib介面。

實現代碼如下:

#import "ViewController.h"#define kURL @"http://avatar.csdn.net/2/C/D/1_totogo2010.jpg"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad{    [super viewDidLoad];    NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self                                                                           selector:@selector(downloadImage:)                                                                             object:kURL];        NSOperationQueue *queue = [[NSOperationQueue alloc]init];    [queue addOperation:operation];    // Do any additional setup after loading the view, typically from a nib.}-(void)downloadImage:(NSString *)url{    NSLog(@"url:%@", url);    NSURL *nsUrl = [NSURL URLWithString:url];    NSData *data = [[NSData alloc]initWithContentsOfURL:nsUrl];    UIImage * image = [[UIImage alloc]initWithData:data];    [self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];}-(void)updateUI:(UIImage*) image{    self.imageView.image = image;}
  1. viewDidLoad方法裡可以看到我們用NSInvocationOperation建了一個後台線程,並且放到NSOperationQueue中。後台線程執行downloadImage方法。
  2. downloadImage 方法處理下載圖片的邏輯。下載完成後用performSelectorOnMainThread執行主線程updateUI方法。
  3. updateUI 並把下載的圖片顯示到圖片控制項中。

 

運行可以看到下載圖片顯示在介面上。

 

第二種方式繼承NSOperation 

在.m檔案中實現main方法,main方法編寫要執行的代碼即可。

如何控制線程池中的線程數?

隊列裡可以加入很多個NSOperation, 可以把NSOperationQueue看作一個線程池,可往線程池中添加操作(NSOperation)到隊列中。線程池中的線程可看作消費者,從隊列中取走操作,並執行它。

通過下面的代碼設定:
[queue setMaxConcurrentOperationCount:5];
線程池中的線程數,也就是並行作業數。預設情況下是-1,-1表示沒有限制,這樣會同時運行隊列中的全部的操作。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.