Cache tableView Cell data

2019-09-16 17:42发布

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.

2条回答
小情绪 Triste *
2楼-- · 2019-09-16 17:48

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.

查看更多
倾城 Initia
3楼-- · 2019-09-16 18:02

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

查看更多
登录 后发表回答