views:

445

answers:

1

I have a method for loading images for UITableViewCell in the background. I use performSelectorInBackground. The problem is these threads are finishing and loading images even though they may not be on the screen anymore. This can be taxing on resources, especially when the use scrolls quickly and lots of cells are created. The images are fairly small and being loaded from the disk (sqlite db), not from a URL.

I've put code in the cell to check to see if it's the most recently displayed cell and I don't load the image if it's not. This works, but it's still creating the threads even though the "expensive" work of loading the image from disk isn't being executed unless it's the most recent cell.

The question is, what's the best way to deal with this? Should I kill existing threads each time the UITableViewCell is reused? How do I go about killing threads invoked by performSelectorInBackground?

Any other suggestions on how to handle this are appreciated.

A: 

You might consider just loading one image at a time. You can still do it on a thread but serialize the loads so as to not over-burden the system.

You could add the visible cells to an array when they become visible, when cells become invisible you can remove them from the list (or just check if they are visible at convenient times). You could also try deferring the load for a brief amount of time to avoid loading an image that is just scrolling by. The thread would pop the first item from the list and load it, then queue another load.

For threading technologies you could have a look at Operation Queues or make a dedicated thread with NSThread. The Concurrency Programming Guide provides a good overview. Although there is nothing wrong with the method you are using.

Sharing data between threads will also require some form of locking to avoid simultaneous access.

Jon Steinmetz