2011-11-10 220 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