Hobbyist
Hobbyist

Reputation: 16212

Does iOS cache images by default in memory? (RAM)

I've been struggling to find out why my application continues to increase in memory as I move throughout the application.

When leaving the view, I make sure to check to see if the controller is de-initialized and it is, but the memory that was added while in the view retains. I've used the instruments tool and it hasn't detected any leaks, and leaving/re-entering the view repeatedly doesn't have any effect on the used memory.

This leads me to believe that iOS by default caches the UIImage into memory, and only frees the memory if the device needs it.

The view that I'm working with is a UICollectionView which shows the user a gallery of pictures that have been uploaded to my server. Currently I have this limited at 10 images per user, but as you can imagine if there's quite a few images and that can increase the memory rather quickly.

Do I need to worry about this memory? Is it default behaviour for the images to stay in memory until the device needs to free some space? I don't want to submit to the application store and get rejected for poor memory-management.

EDIT: It's also fair to note that I am constructing the image using the UIImage(data: NSData) constructor.

Upvotes: 0

Views: 331

Answers (1)

Technologeeks
Technologeeks

Reputation: 7907

iOS does natively cache plenty of memory. The underlying support for that is in libcache, which UIKit uses internally, in a way that is inaccessible to you.

During times of "memory pressure", that is, when RAM is low, an event (technically , a knote) is broadcast to all listeners. Your app is listening because the frameworks automatically open a kevent file descriptor, and react to it with the well known didReceiveLowMemoryWarning. Remember, there's no swap in iOS (discounting compressed RAM for the scope of this answer), so this happens quite frequently.

Even before didReceiveLowMemoryWarning is passed to you, libcache uses the malloc feature of "zone pressure relief" , which you can see for yourself in :

...
   /* Empty out caches in the face of memory pressure. The callback may be NULL. Present in version >=
 8. */
    size_t      (*pressure_relief)(struct _malloc_zone_t *zone, size_t goal);
} malloc_zone_t;

Thus, images (main consumers of memory) will be purged if necessary, and therefore should be of much concern to you. That said, if you know you don't want a given UI object anymore, you can of course dispose of it explicitly. Of course, if you have any additional resources that cannot be auto-purged in this way, you should handle them in the delegate. Because if you don't, Jetsam will jettison your app (i.e. kill you with an untrappable -9), and probably slay a few innocents in your priority band as well.

Upvotes: 2

Related Questions