Question

I am planning to cache the images from a server and use show it as a sort slide show in my App. I would be asynchronously loading the images.

I have two options:

  1. Either to cache the images as a File and use it whenever necessary.
  2. Cache the images objects in memory and use it when ever necessary and write it in to files when Application quits.

Which one would be better?

Please let me know if you you have any kind of suggestions regarding caching images.

Was it helpful?

Solution

Your second approach has 2 major flaws:

  1. If there's too many images then your application will get low memory warning and you'll have to dispose your images from memory anyway
  2. It's also not a good idea to save all images to file on application quit - it is not guaranteed that your saving code will finish on application exit (e.g. if it takes too long system may just terminate your app and your images will be lost)

I'd suggest saving images to files right after you download them and keep in memory reasonable number of images you need to show without visible delay (loading extra images when required and disposing of unnecessary ones)

OTHER TIPS

I would recommend you the first option. Leaves you more flexibility, e.g. when the data size increases the memory size.

I'd do it like this: Have a NSMutableDictionary with the cached images (as UIImage objects). If the image is not in the cache, look whether it's available as a file. If it's not available as a file, load it, put it into your dictionary and also write it to a file.

As for where to write the files to: you can either use the NSTemporaryDirectory() or create a directory inside your NSLibraryDirectory (use NSSearchPathForDirectoriesInDomains to locate it). The later has the advantage/disadvantage that it will be in the iTunes backup (whether that's an advantage or not depends on the use case). Using the Library directory is Apple's recommended way of storing data that is backed up but does not appear in the iTune's file exchange thingy (Documents directory).

I have started using EGOImageView to handle my caching; it's very versatile and handles the intricacies of caching for you.

It works very well for pulling images via http, you can find it on the EGO developer website here

http://developers.enormego.com/

For image caching solution on iOS platform, you might want to consider SDWebImage framework available at: https://github.com/rs/SDWebImage. It is very easy to integrate and takes care of all your image caching worries.: read more about the working here: https://github.com/rs/SDWebImage#readme

We recently picked this up for our app and it works great.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top