从NSDocumentDirectory为UITableViewCells延迟加载图像?

时间:2010-06-10 08:06:20

标签: objective-c uitableview ios4 uiimage

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

这是用于立即加载图片的代码段:

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];
}

在每个单元格中“延迟加载”图像的最佳方法是什么,以避免在滚动中滞后?

1 个答案:

答案 0 :(得分:7)

查看SDWebImage存储库。它提供了执行异步图像加载的所有功能。

<强>更新

我刚注意到README中存在一些拼写错误,因此下载本地文件可能无法按预期工作。

以下是一些示例代码。视图控制器有一个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;
}