5

I'm trying to improve scrolling performance on a UITableView that uses cells with images fetched from the web, but stored in the NSCachesDirectory. The cells have a custom content view to draw the contents (an image).

When I use a placeholder image from the app bundle, using [UIImage imageNamed:@"Placeholder.png"], scrolling performance is super fast.

When I load an image from the disk cache (NSCachesDirectory) using [UIImage imageWithContentsOfFile:cachePath], scrolling performance gets worse.

According to the documentation, imageNamed: caches the image and imageWithContentsOfFile: does not.

How to use UIImage's system cache when using imageWithContentsOfFile: ?

Thanks a bunch!

Martijn Thé
  • 4,674
  • 3
  • 29
  • 42
  • You may want to see a [recent question](http://stackoverflow.com/questions/18750686/how-to-find-uiimage-bottleneck#comment27641913_18750686) of mine where I resolved the problem by storing an uncompressed image. – Victor Engel Sep 28 '13 at 00:12

3 Answers3

8

It seems to be possible to use the path to an image in the NSCachesDirectory as argument for the [UIImage imageNamed:] method. The method accepts relative paths (relative to the app bundle), e.g.: @"../Library/Caches/SomeCachedImage.png" works.

UIImage automatically caches the image in memory if it is used multiple times, which improves the performance when an image is used multiple times in a table view.

Martijn Thé
  • 4,674
  • 3
  • 29
  • 42
3

The problem is most likely that you are loading and decompressing the image in the main run loop. This will block the user interface for a short time. You get much better performance if you do the loading and decompression in a seperate thread and only set the image in the main loop. (Which is also required for user interface changes, which setting an image on a UIImageView is)

This will require some more infrastructure. Like for example a notification scheme or key value observing.

Stefan Arentz
  • 34,311
  • 8
  • 67
  • 88
  • Yes, that is exactly the problem. I was hoping for an off the shelf solution. But I guess it's not there. Thanks for the answer. – Martijn Thé Feb 22 '10 at 13:52
  • If you like the answer you should upvote it or mark it as solved. – Stefan Arentz Feb 22 '10 at 15:26
  • UIImage decompresses image bitmap data lazily, so in many (most?) situations this won't really help - loading from disk will happen on your background thread, but the decompression (which often takes longer than loading the data) will happen when you set the image, which has to happen on the main thread. – Nick Forge Sep 29 '11 at 01:49
0

You can't. imageWithContentsOfFile: will always load the image from file (though lazily). What you can do is create an in memory cache of you own with NSArrays or NSDictionaries, depending on how you'll want to do the lookup.

Mihai Damian
  • 11,193
  • 11
  • 59
  • 81