开发者

Lazy load images for UITableViewCells from NSDocumentDirectory?

开发者 https://www.devze.com 2023-01-02 19:09 出处:网络
I have a UITableView in my app in which I load several images from the NSDocumentDirectory. It works, but when scrolling up and down, the app seems to freeze a bit, most likely because of the images b

I have a UITableView in my app in which I load several images from the NSDocumentDirectory. It works, but when scrolling up and down, the app seems to freeze a bit, most likely because of the images being served in the main thread, effectively blocking the tableView from scrolling until it's loaded. My problem is that I don't know how to load them in later, a "lazy load" feature, while scrolling.

This is the code snippet used to load the images now:

imagesPath = [NSString stringWithFormat:@"%@/images/", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)开发者_JAVA百科 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];
}

What is the best way to "lazy load" the images in each cell to avoid lagging in the scrolling?


Take a look at the SDWebImage repository. It provides everything to perform asynchronous image loading.

Update

I just noticed that there is some typos in the README, so downloading a local file may not work as expected.

Here is some sample code. The view controller has an UIImageView outlet and wants to load the image.jpg file. It implements the SDWebImageManagerDelegate protocol:

- (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

精彩评论

暂无评论...
验证码 换一张
取 消