2015-05-01 192 views
0

我正在開發一個iOS應用程序。並通過JSON獲取圖像並在桌面上顯示。使用此方法dispatch_async(kBgQueue, ^{...和圖像顯示在桌面視圖上,但所有圖像都顯示在一個單元格上並自動回收。圖像可能會在一段時間後改變,也可以使用佔位符圖像。使用兩個字符串顯示圖像一個字符串可用於圖像名稱和第二個字符串可用於URL。然後連接字符串以顯示在收集視圖中相同問題的圖像。任何其他方法在tableview和collection視圖中快速顯示圖像。
我的代碼:加載JSON圖像快速

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 

    { 
     mycell=[tableView dequeueReusableCellWithIdentifier:@"cell"]; 
     UILabel *mylabel = (UILabel *)[mycell viewWithTag:100]; 
     NSDictionary *dic=[str objectAtIndex:indexPath.row]; 
     GRLanguage *sharedManager = [GRLanguage sharedManager]; 
     if ([sharedManager.LanguageCode isEqual:@"hi"]) { 
      mylabel.text=[dic objectForKey:@"hindi_name"]; 
     }else if ([sharedManager.LanguageCode isEqual:@"pa"]) 
     { 
      mylabel.text=[dic objectForKey:@"punjabi_name"]; 
     }else 
     { 
      mylabel.text=[dic objectForKey:@"name"]; 
     } 


     [mycell setBackgroundColor:[UIColor clearColor]]; 
     UIImageView *img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"back copy.png"]]; 
     self.tableview.backgroundView =img; 


     dispatch_async(kBgQueue, ^{  //Using For Lazy Loading 
      UIImageView *imagetlt = (UIImageView *)[mycell viewWithTag:1]; 
      NSString *image =[dic objectForKey:@"image_path"]; 
      NSString *[email protected]"http://webapp.opaxweb.net/images/"; 
      path=[path stringByAppendingString:image]; 
      NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:path]]; 
      if (image == nil) { 
       [imagetlt setImage:[UIImage imageNamed:@"rel_circle.png"]]; 
      }else 
      { 
       dispatch_async(dispatch_get_main_queue(), ^{ 
        // UITableViewCell*img = (id) [tableView cellForRowAtIndexPath:indexPath]; 
        imagetlt.image = [UIImage imageWithData: imageData]; 
       }); 

      } 


    }); 
    return mycell; 
} 
+0

建議 - 在GitHub中的AsyncImageLoader。 –

+0

使用AFNetworking .. –

回答

0

你有一個嚴重的問題。您創建一個單元格,然後嘗試異步加載圖像並嘗試將其存儲在單元格中。這是行不通的。細胞將被重複使用。到圖像到達時,單元格可能會顯示完全不同的數據。

以下是您的操作:您將從URL返回的圖像保存在內存中或存儲在文件中。在cellForRowAtIndexPath中,您嘗試檢索緩存的圖像並存儲該圖像,或者存儲佔位符圖像並開始異步下載。下載完成後,將圖像放入緩存並調用reloadRowsAtIndexPaths:以便重新加載該行。

如果在異步下載運行時項目可以更改其行(因爲用戶添加或刪除行或更改排序順序等),甚至更好,當異步下載結束時,您會確定哪一行包含該項目(下載開始時可能不包含該項目),併爲該行調用reloadRowsAtIndexPaths:。