David
David

Reputation: 998

Caching images in memory on iOS, what is smaller : a UIImage or NSData object?

I'm working on an image cache on iOS. Images are downloaded from URL and stored in a NSDictionary as a UIImage (I don't want or need "on disk" cache).

The question is : should I store images in my dictionary as UIImage or NSData ? Which one is significantly smaller in term of memory ?

Upvotes: 3

Views: 4834

Answers (2)

Rob Napier
Rob Napier

Reputation: 299605

UIImage has optimizations for automatically responding to low memory situations and releasing its cached representations. From the UIImage reference:

In low-memory situations, image data may be purged from a UIImage object to free up memory on the system. This purging behavior affects only the image data stored internally by the UIImage object and not the object itself. When you attempt to draw an image whose data has been purged, the image object automatically reloads the data from its original file. This extra load step, however, may incur a small performance penalty.

Generally speaking you should leave image data in a UIImage.

If images are something you can re-fetch as needed, you should consider NSPurgeableData, or your own objects, together with an NSCache rather than an NSDictionary. NSCache is particularly nice memory stored in it can be automatically released by the OS, even while you are suspended, avoiding you being terminated while in the background. UIImage does a lot of this for you already, but NSCache would allow you to free all the data rather than just the uncompressed data.

Upvotes: 7

Jano
Jano

Reputation: 63707

NSData is smaller because it stores the compressed version of the image. But decompressing takes time, so as long as memory allows, cache the UIImage and clean the cache if you get a memory warning.

Upvotes: 5

Related Questions