[英]What's an ideal way to load/clear data to UICollectionView from Bundle.main?
I have about 100 GIFs in the main bundle.我的主包中有大约 100 个 GIF。 I'm loading everything during viewDidLoad() in an array.我在 viewDidLoad() 期间将所有内容加载到数组中。 This array is the datasource for the UICollectionView.这个数组是 UICollectionView 的数据源。 The problem is that these GIFs are taking a lot of memory which is causing slowness and lead to app crash due to memory.问题是这些 GIF 占用了大量内存,这会导致运行缓慢并导致应用程序因内存而崩溃。 When I start scrolling, the memory debugger shows up to 800 mb+ and then crashes.当我开始滚动时,内存调试器显示高达 800 mb+,然后崩溃。
I considered integrating 3rd-party libraries to optimize the GIFs performances.我考虑集成第 3 方库来优化 GIF 性能。 Then I thought about creating some sort of local caching solution where I can offload memory and fetch data when needed in the background once the cell goes offview.然后我考虑创建某种本地缓存解决方案,一旦单元格离开视图,我可以在后台卸载内存并在需要时获取数据。 Is this a right approach or am I overcomplicating things?这是一种正确的方法还是我把事情复杂化了?
viewDidLoad
.在viewDidLoad
加载 gif 包 url(仅 url,而不是图像数据)。override func viewDidLoad() {
gifUrls = ...
}
// In collection view cell
imageView = BBAnimatedImageView(frame: frame)
collectionView(_:cellForItemAt:)
.在collectionView(_:cellForItemAt:)
异步加载 gif。func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellReuseID, for: indexPath)
cell.tag = indexPath.item
let url = gifUrls[indexPath.item]
DispatchQueue.global().async {
guard let data = try? Data(contentsOf: url) else { return }
let gif = BBAnimatedImage(bb_data: data)
DispatchQueue.main.async {
guard cell.tag == indexPath.item else { return }
cell.imageView.image = gif
}
}
}
As @rmaddy said you could load gifs in cycle of visible cells by these methods:正如@rmaddy 所说,您可以通过以下方法在可见单元格的循环中加载 gif:
func collectionView(_ collectionView: UICollectionView,
willDisplay cell: UICollectionViewCell,
forItemAt indexPath: IndexPath)
And:和:
func collectionView(_ collectionView: UICollectionView,
didEndDisplaying cell: UICollectionViewCell,
forItemAt indexPath: IndexPath)\
Load gif on willDisplay
and offload it on didEndDisplaying
.负载GIF willDisplay
和卸载它didEndDisplaying
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.