2010-06-10 43 views
6

我有一个UITableView在我的应用程序中,我从NSDocumentDirectory加载几个图像。它工程,但是当上下滚动时,应用程序似乎冻结了一点,很可能是因为图像在主线程中服务,有效地阻止了tableView滚动,直到它加载。我的问题是,我不知道如何在以后加载它们,“滚动加载”功能。从NSDocumentDirectory为UITableViewCells提供延迟加载图像?

这是所使用的代码片断现在加载图片:

imagesPath = [NSString stringWithFormat:@"%@/images/", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]]; 
if ([fileManager fileExistsAtPath:[imagesPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%d.png", rowID]]]) { 
    UIImage *image = [[UIImage alloc] initWithContentsOfFile:[imagesPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%d.png", rowID]]]; 
    // If image contains anything, set cellImage to image. If image is empty, use default, noimage.png. 
    if (image != nil){ 
     // If image != nil, set cellImage to that image 
     cell.cellImage.image = image; 
    } 
    [image release]; 
} 

什么是“懒加载”的每个细胞图像,以避免在滚动滞后的最好方法?

回答

7

查看SDWebImage存储库。它提供了执行异步映像加载的所有内容。

更新

我只注意到有自述一些错别字,因此下载的本地文件可能无法正常工作。

这是一些示例代码。视图控制器有一个UIImageView插座,并且想要加载image.jpg文件。它实现SDWebImageManagerDelegate协议:

- (IBAction)loadImage:(id)sender { 
    SDWebImageManager *manager = [SDWebImageManager sharedManager]; 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *destPath = [documentsDirectory stringByAppendingPathComponent:@"image.jpg"]; 
    NSURL *url = [NSURL fileURLWithPath:destPath]; 
    UIImage *cachedImage = [manager imageWithURL:url]; 
    if (cachedImage) 
    { 
     imageView.image = cachedImage; 
    } 
    else 
    { 
     // Start an async download 
     [manager downloadWithURL:url delegate:self]; 
    }  
} 

- (void)webImageManager:(SDWebImageManager *)imageManager didFinishWithImage:(UIImage *)image 
{ 
    imageView.image = image; 
} 
+0

我不想下载图像,我试图从NSDocumentDirectory加载图像。 – Emil 2010-06-10 09:05:08

+0

下载应理解为访问NSURL支持的任何资源。 NSURL可用于多种协议:http,ftp或文件。将您的路径转换为NSURL并“下载”您的本地文件。 – 2010-06-10 09:28:56

+0

我正在尝试,但它不起作用! NSURL从字符串中加载:'file:// var/mobile/Applications/RANDOMIDENTIFIER/Documents/images/10.png'。 – Emil 2010-06-10 20:34:35