开发者

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

开发者 https://www.devze.com 2023-04-12 20:36 出处:网络
I\'m working on an image cache on iOS. Images are downloaded from URL and stored in a NSDictionary as a UIImage (I do开发者_如何学Pythonn\'t want or need \"on disk\" cache).

I'm working on an image cache on iOS. Images are downloaded from URL and stored in a NSDictionary as a UIImage (I do开发者_如何学Pythonn'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 ?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号