5 tips to reduce memory issues in iOS apps

Our recent game development experience with Letter Blocks 3D has shown once again that shared RAM system is one of the biggest bottlenecks on iOS devices. This became even more relevant with iOS 4 and its multitasking support. Careless users tend to leave a lot of apps and browser tabs to stay in background and consume RAM. Under such conditions an app may receive memory warnings and get killed at any moment… Thus it is critical for an app to handle memory warnings properly and keep memory footprint as small as possible to avoid being killed. Here’s what we discovered to be helpful:

1. Use virtual memory

iOS doesn’t use swap file but it does support virtual memory. If an app keeps a lot of data in memory for random access (like vocabulary in Letter Blocks 3D) you want to organize it as a mapfile rather then loading it to RAM with malloc(). An easiest way to do that is to call NSData initWithContentsOfMappedFile:

2. Avoid stacking autoreleased objects
When you instantiate objects like NSString with no explicit allocation they live until the release of your autorelease pool – typically until your app quits. Extensive usage of such techniques may lead to a lot of garbage in RAM. Use NSString initWithContentsOfFile: so you can later release it instead of NSString stringWithContentsOfFile:. The same rule applies to UIImage imageNamed: – this is not recommended to use for image loading.

3. Handle memory warnings
Unload unnecessary resources when handling memory warning. Even if you can’t unload any of your stuff call [super didReceiveMemoryWarning] in all your UIViewControllers. That will by default free some resources like UI controls on non-front views. Failing to handle this event may make iOS decide that your app deserves killing.

4. Consider limited usage of animated view transitions
Animations like flip transition are noticed to cause RAM usage spikes when executed. This feature is very neat and should be used in many cases but it may trigger memory warnings in a heavily loaded multitasking environment. In particular we strongly recommend to avoid animating OpenGL views.

5. Test your memory footprint on device

Use instruments to test. The most useful tools are Allocations, Leaks and Activity Monitor. Testing on simulator is not relevant in most cases since its memory footprint tends to be completely different. Once you test you can figure out how much RAM each part of your app uses, where are the bottlenecks and how you can optimize.

Happy coding :)