I have a PhotoGrid
with three photos on each row, implemented using UITableView
.
I have an in-memory cache (using NSCache) which has a capacity for 100 images, so at one time I will be having at most 100 images in memory even though I have thousands of images on disc to show up in the Grid.
All my images are 4KB-20KB JPEGs.
So with this infrastructure, the images are continuously loaded and unloaded from NSCache when the user scrolls through the photo grid. With normal scrolling everything looks good, I get around 55-58 fps.
When the user starts scrolling faster back and forth, I have two cases:
If I separate out the image loading task from main thread, I end up missing images on the photo grid, because my cells are displayed before the images are read into memory.
(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ UIImage *image = getImageFromCacheForImagePath:imagePath; dispatch_async(dispatch_get_main_queue(), ^{ cell.leftGridItem.imageView.image = image; }); }); }
If I have the images loading task on the main thread, there is a stutter. I get around 36-45fps.
(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UIImage *image = getImageFromCacheForImagePath:imagePath; cell.leftGridItem.imageView.image = image; }
getImageFromCacheForImagePath:imagePath
gets the image immediately from NSCache if it existed, if not, the image is loaded from file and is set into NSCache for later usage, but I set the limit of NSCache
to 100.
Things I tried/tweaked:
- Avoid
clipsToBounds
for grid image views. - Loading images on background thread.
- Use of
NSOperation
Queues. - Loading images in batches of 100 (works, but with fast scrolling, image loading time was delayed).
I am trying to achieve the same feel as native Photos app.
Your suggestions are appreciated.
^{
which looks like it should start a new code block but doesn't seem correct to me). We tried to help you get it formatted right, but it's not really clear. – Kittykitwe