learningthings learningthings - 9 months ago 44
Swift Question

Tableview scroll too slow loading images

My issue is that in my app I load images in a table view. When I scroll through the table view it is really slow and stops scrolling sometimes. I looked online and saw that using dispatch would help. I tried that with the code below and my app crashes saying that it is nil.


dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {

let parseImage: PFFile = objectSong.valueForKey("picture") as PFFile
var pic: UIImage = UIImage(data: parseImage.getData())!

dispatch_async(dispatch_get_main_queue()) {
cell.imageView.image = pic <-- crash happens here

Previous code used to load table view cells:

let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as TableViewCell
let objectSong: PFObject = object as PFObject

cell.songImage.image = UIImage(data: parseImage.getData())

Answer Source

That approach cannot work.

Remember how a tableview with reusable cells works. The same cell is used for different rows. So if you download an image asynchronously and try to store it in the cell, the cell might be used for a different row. And anyway, you set the image on the background thread, and that is going to cause trouble.

Here's what you do: You cache images. When the cell is loaded, you look for a cached image. If it is there you set it, if it is not there you set a placeholder image and start the download.

When the download is finished, you cannot put the image into the cell. Instead, you add it to the cache. Then you figure out which row should display the image (in case rows have been added or removed), then you reload that row on the main thread. The reload will then pick up the image from the cache.