Polly Polly - 5 months ago 31
iOS Question

IOS memory and battery management - Memory vs Work

I am new to IOS and coming from pcs I am trying to get a feel for managing memory and battery resources.

I have a UIImageView subclass which is is very light (it's an image placeholder with a handful of methods). This subClass is repeatedly added to, and removed from, several root views. I hold an IBOutlet reference to the subClass on each root view.

Would you:

  • Simply add/remove the subClass from the root view (and keep it in memory)?


  • Create and destroy the subClass instance each time (freeing the memory but extra work)?

Is this worth considering or am I worrying over nothing?

Would your answer be the same if the UIImageView subClass was very large?

Is there a way of measuring these matters?

Answer Source

I would go with your first option, keeping it in memory. This is just because I think it is handy to keep my views alive and reuse them. This means that they will remember their state and content and that helps out in many cases. I usually write methods to reset the content or refresh it when needed.

Keeping it in memory might also increase the loading of the view slightly, but usually you do not notice the difference, and I see people using both ways.

And yes, I would say you are worrying a bit too much, especially if you think this decision would affect battery.

Regarding memory management, keeping the imageview in memory or releasing/recreating consumes the exact same amount of memory as long as you only have one imageview that you are using. The only difference is that you are allocating and releasing it repeatedly if you are recreating it.

You could however get memory issues if you start creating new imageviews every time the user opens them and never letting go of them, but that means you are doing something fundamentally wrong in your programming.

As long as you know what you are doing, no need to worry about the amount of memory in a case like this - there's plenty. Start worrying if you are handling large images.

Especially if you use ARC there is not much to worry about, just start hacking away. If you are managing memory manually, I do recommend trying to reuse stuff because that causes less headache and risk of giant leaking. Use leaktools and analyze tool to make sure in this case.