代码之家  ›  专栏  ›  技术社区  ›  Emil

从nsdocumentdirectory为uitableviewcells延迟加载图像?

  •  6
  • Emil  · 技术社区  · 15 年前

    我有一个 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 回复  |  直到 12 年前
        1
  •  7
  •   Laurent Etiemble    15 年前

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