缓存 tableView Cell 数据 [英] Cache tableView Cell data

查看:36
本文介绍了缓存 tableView Cell 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我正在使用 URL 下载一些图像并将它们放入 cell.imageView[indexPath.row](这是一个内部带有 imageView 的自定义单元格).我一次可以看到两个单元格,我注意到该方法

In my application I'm downloading some images using the URL and put them in the cell.imageView[indexPath.row] (it's a custom cell with an imageView inside). I can see two cells at a time and I noticed that the method

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> CustomCell {
}

每次显示单元格时都会调用它.所以我的应用程序继续从服务器下载图像,应用程序结果非常慢.

It's called every time the cell will be displayed. So my app continue to download the image from the server and the app result very slow.

我想知道是否可以缓存我已经看到的单元格的数据,所以如果我在我的 tableView 中向上滚动,我不需要重新下载图像!代码方面我想调用上面写的 func 只有当我向下滚动表格而不是我已经看到的单元格时.

I would like to know if it's possible to cache the data of the cells I already saw, so I don't need to re-download the image if I scroll up in my tableView! Code speaking I would like to call the func written above only if I scroll down the table and not for the cells I already saw.

推荐答案

不要重新发明轮子!
看看 NSCache,它就像一个可变字典,但它是线程安全的.

Do not reinvent the wheel!
Take a look at NSCache, it works like a mutable dictionary but it thread safe.

NSCache 对象在几个方面不同于其他可变集合:

NSCache objects differ from other mutable collections in a few ways:

NSCache 类包含各种自动删除策略,确保它不会使用过多的系统内存.这如果内存需要,系统会自动执行这些策略其他应用.调用时,这些策略会删除一些项目来自缓存,最大限度地减少其内存占用.

The NSCache class incorporates various auto-removal policies, which ensure that it does not use too much of the system’s memory. The system automatically carries out these policies if memory is needed by other applications. When invoked, these policies remove some items from the cache, minimizing its memory footprint.

您可以从不同的缓存中添加、删除和查询项目线程而不必自己锁定缓存.

You can add, remove, and query items in the cache from different threads without having to lock the cache yourself.

与 NSMutableDictionary 对象不同,缓存不会复制键放入其中的对象.

Unlike an NSMutableDictionary object, a cache does not copy the key objects that are put into it.

这些特性对于 NSCache 类是必要的,因为缓存可能决定在幕后异步自动变异自身如果调用它来释放内存.

These features are necessary for the NSCache class, as the cache may decide to automatically mutate itself asynchronously behind the scenes if it is called to free up memory.

您可以使用图像的 URL 和它们作为值来键入图像.
文档.
NSHipster 帖子.

You can key your images using their URL and them as a value.
Documentation.
NSHipster post.

这篇关于缓存 tableView Cell 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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