Cache tableView Cell data

穿精又带淫゛_ 提交于 2019-12-12 06:32:52

问题


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.

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.


回答1:


You can but it takes a fair bit of work so the nice people at SDWebImage make a library to download / cache / fetch / manage your image URLs just swap your image getting code with this category for UIImageview, this gives UIImageView.sd_ methods.

Also with cells implement prepareForReuse() and cancel the fetch with sd_cancel




回答2:


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

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

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.

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

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.

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



来源:https://stackoverflow.com/questions/36646968/cache-tableview-cell-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!