ios UIImageView異步加載網絡圖片


方法1:在UI線程中同步加載網絡圖片

  1. UIImageView *headview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];  
  2.   
  3. NSURL *photourl = [NSURL URLWithString:@"http://www.exampleforphoto.com/pabb/test32.png"];  
  4. //url請求實在UI主線程中進行的  
  5. UIImage *images = [UIImage imageWithData:[NSData dataWithContentsOfURL:photourl]];//通過網絡url獲取uiimage  
  6. headview.image = images;  

這是最簡單的,但是由於在主線程中加載,會阻塞UI主線程。所以可以試試NSOperationQueue,一個NSOperationQueue 操作隊列,就相當於一個線程管理器,而非一個線程。因為你可以設置這個線程管理器內可以並行運行的的線程數量等等。

 

方法2:使用NSOperationQueue異步加載

  1. 下面就是使用NSOperationQueue實現子線程加載圖片:  
  2. - (void)viewDidLoad  
  3. {  
  4.     [super viewDidLoad];  
  5.       
  6.     NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];  
  7.       
  8.     self.imageview  = [[[UIImageView alloc] initWithFrame:CGRectMake(110, 50, 100, 100)] autorelease];  
  9.     [self.imageview setBackgroundColor:[UIColor grayColor]];  
  10.     [self.view addSubview:self.imageview];  
  11.       
  12.     NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(downloadImage) object:nil];  
  13.     [operationQueue addOperation:op];  
  14. }  
  15.   
  16. - (void)downloadImage  
  17. {  
  18.     NSURL *imageUrl = [NSURL URLWithString:HEADIMAGE_URL];  
  19.     UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageUrl]];  
  20.     self.imageview.image = image;  
  21. }  

不過這這樣的設計,雖然是異步加載,但是沒有緩存圖片。重新加載時又要重新從網絡讀取圖片,重復請求,實在不科學,所以可以考慮第一次請求時保存圖片。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM