2011-11-10 168 views
1

什麼是超極簡單的方式來加載在的UITableViewCell圖像異步說給予IMAGEURL而無需子類的UITableViewCell,即:標準的UITableViewCell加載圖像異步

回答

0

我知道的最簡單的方法是使用SDWebImage庫。這是一個鏈接,介紹如何利用SDWebImage庫異步加載頭像。

SDWebImage是ImageView的擴展。下面是用法:

// load the avatar using SDWebImage 
    [cell.imageView setImageWithURL:[NSURL URLWithString:tweet.profileImageUrl] 
        placeholderImage:[UIImage imageNamed:@"grad_001.png"]]; 

,這裏是引用的文章:

Implementing Twitter Search

+0

我在說標準的UITableViewCell – xonegirlz

+0

@xonegirlz標準的UITableViewCell也有一個imageView。 SDWebImage只是擴展了imageView。 SDWebImage使用類別來擴展UIImageView。 – azamsharp

+0

yea..sorry關於..這個圖書館是驚人的!謝謝 – xonegirlz

0

你可以使用一個線程。將按鈕放在字典上。使用該線程。然後在方法setImage:您可以放置​​圖像。

NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; 

     [dictionary setObject:url forKey:@"url"]; 
     [dictionary setObject:image forKey:@"image"]; 
     [NSThread detachNewThreadSelector:@selector(setImage:) 
           toTarget:self 
           withObject:dictionary]; 
1

在您的m,包括客觀的C運行時:

#import <objc/runtime.h> 

在頂部你的@implementation部分,定義一個靜態常量以供使用:

static char * const myIndexPathAssociationKey = ""; 

在你的cellForRowAtIndexPath,添加以下代碼:

// Store a reference to the current cell that will enable the image to be associated with the correct 
// cell, when the image subsequently loaded asynchronously. Without this, the image may be mis-applied 
// to a cell that has been dequeued and reused for other content, during rapid scrolling. 
objc_setAssociatedObject(cell, 
         myIndexPathAssociationKey, 
         indexPath, 
         OBJC_ASSOCIATION_RETAIN); 

// Load the image on a high priority background queue using Grand Central Dispatch. 
// Can change priority by replacing HIGH with DEFAULT or LOW if desired. 
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0); 
dispatch_async(queue, ^{ 
    UIImage *image = ... // Obtain your image here. 

    // Code to actually update the cell once the image is obtained must be run on the main queue. 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     NSIndexPath *cellIndexPath = (NSIndexPath *)objc_getAssociatedObject(cell, myIndexPathAssociationKey); 
     if ([indexPath isEqual:cellIndexPath]) { 
     // Only set cell image if the cell currently being displayed is the one that actually required this image. 
     // Prevents reused cells from receiving images back from rendering that were requested for that cell in a previous life. 
      [cell setImage:image]; 
     } 
    }); 
}]; 

最後,支持最佳性能時,舊設備快速滾動,您可能想先......對於加載最近請求的圖像,看this thread for asynchronously loading cell images using a last-in first-out stack and GCD

+0

WOWW !!!這真太了不起了!!!非常感謝!你爲我節省了一晚的編碼! – igrek

+0

但這最終與EXC_BAD_ACCESS行「if([indexPath isEqual:cellIndexPath]){」任何線索? – igrek

+1

已修復,OBJC_ASSOCIATION_ASSIGN取代OBJC_ASSOCIATION_RETAIN在objc_setAssociatedObject – igrek