延迟加载图像在UITableViewCell [英] Lazy load images in UITableViewCell

查看:132
本文介绍了延迟加载图像在UITableViewCell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有大约50个自定义单元格在我的UITableView。我想在单元格中显示一个图像和一个标签,其中我从URL获取图像。

I have some 50 custom cells in my UITableView. I want to display an image and a label in the cells where I get the images from URLs.

我想做一个延迟加载的图像,所以UI不冻结当图像正在加载时。我试图在单独的线程中获取图像,但我必须加载每个图像每次一个单元格再次可见(否则重用单元格显示旧的图像)

I want to do a lazy load of images so the UI does not freeze up while the images are being loaded. I tried getting the images in separate threads but I have to load each image every time a cell becomes visible again (Otherwise reuse of cells shows old images)

像Facebook负载图像只用于当前可见的单元格,一旦图像加载,它们不会再次加载。有人可以告诉我如何复制此行为。

Apps like Facebook load images only for cells currently visible and once the images are loaded, they are not loaded again. Can someone please tell me how to duplicate this behavior.

感谢。

>

尝试在NSMutableDictionary对象中缓存图像会在用户快速滚动时产生问题。我得到图像只有当滚动完全停止和清除缓存内存警告。但应用程序总是得到一个内存警告(由于图像缓存的大小),并清除缓存重新加载。

Edit
Trying to cache images in an NSMutableDictionary object creates problems when the user scrolls fast. I am getting images only when scrolling completely stops and clearing out the cache on memory warning. But the app invariably gets a memory warning (due to size of images being cached) and clears the cache before reloading. If scrolling is very fast, it crashes.

欢迎任何其他建议

推荐答案

在后台线程上加载图像仍然是个好主意。如果你不想每次重新加载它们,我建议设置一个NSMutableDictionary并将图像存储在那里。您可以使用某些唯一标识符(如行ID或图像名称)作为每个图像的键。

Loading the images on a background thread is still a good idea. If you didn't want to reload them each time, I'd suggest setting up an NSMutableDictionary and storing the images in there. You could use some unique identifier, like the row ID or even the name of the image, as the key for each image.

加载单元格时,您可以发送一个objectForKey:消息到NSMutableDictionary检索特定单元格的图像(基于它的唯一键)。如果它返回nil,这意味着图像从缓存丢失,你需要你的背景图像加载线程去检索它。否则,将返回要显示的表单元格的适当图像。在内存警告中,您可以清除此缓存的图像,而不会产生任何负面影响(除了强制他们根据需要重新加载)。

When loading a cell, you'd send an objectForKey: message to the NSMutableDictionary to retrieve the image for that particular cell (based on your unique key for it). If it returns nil, that means that the image is missing from the cache and you need your background image loading thread to go retrieve it. Otherwise, you will get back the appropriate image for your table cell to display. On a memory warning, you could clear out this cache of images with no adverse effects (aside from forcing them to be reloaded again on demand).

这篇关于延迟加载图像在UITableViewCell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆