user2526811
user2526811

Reputation: 1253

Load images from Document Directory in ios sdk

I implemented the collection view on which I displays the images from the document directory.

But due to images load from document the collection view is not scroll smoothly.

If the images load from main bundle then it works fine.

My code is as follow:

UIImageView *img=[[UIImageView alloc]init];
img.image=[UIImage imageWithContentsOfFile:[[arr_images objectAtIndex:indexPath.row]valueForKey:@"Image_path"]];
img.contentMode=UIViewContentModeScaleAspectFit;
cell.backgroundView=img;

Should I use threading? If yes, How can i do that? How can I solve this??

Upvotes: 0

Views: 1608

Answers (2)

Wain
Wain

Reputation: 119031

Presumably the images in the bundle are smaller than those in the documents folder, otherwise there is no difference.

Yes, you should use threading. Using GCD is a good option, the main thing to take care of is to not directly use the cell (you don't know if it will have been reused by the time the image is loaded), but rather to use the indexPath inside the block to get the cell and, if it isn't nil, update the image.

Upvotes: 0

Abhi Beckert
Abhi Beckert

Reputation: 33369

No need to use threading. Loading the images occasionally is fine, the problem is you are loading the images constantly.

Loading from the main bundle probably works fine because NSBundle is caching the images for you. You can do the same yourself using NSCache.

So instead of this:

img.image=[UIImage imageWithContentsOfFile:[[arr_images objectAtIndex:indexPath.row]valueForKey:@"Image_path"]];

Do something like:

static NSCache *cache = nil;
if (!cache) {
    cache = [[NSCache alloc] init];
    [cache setCountLimit:10]; // check how much RAM your app is using and tweak this as necessary. Too high uses too much RAM, too low will hurt scrolling performance.
}

NSString *path = [[arr_images objectAtIndex:indexPath.row]valueForKey:@"Image_path"];
if ([cache objectForKey:path]) {
    img.image=[cache objectForKey:path];
} else {
    img.image=[UIImage imageWithContentsOfFile:path];
    [cache setObject:img.image forKey:path];
}

If in the end you do find you need to use threading, then I would use a GCD thread to load the image, but then insert that image into the same NSCache object I created in my sample code here. Basically use a background thread to try and predict which images need to be preloaded, but allow NSCache to decide how long to keep those images in RAM before destroying them.

Upvotes: 6

Related Questions