Channels ▼
RSS

Testing

Managing Memory on iOS


When Memory Gets Low

The moment the amount of free memory hits a low point, iOS starts warning its apps, both active and inactive. The apps must respond by releasing any unneeded objects and disposing of any resources that can be rebuilt or reloaded. If an app fails to respond as such, it can be marked for termination.

There are two ways to trap a low-memory warning. One way is with the method applicationDidReceiveMemoryWarning. This is a delegate method, declared by the protocol UIApplicationDelegate. Its single input argument is a pointer to the active UIApplication object. If the method is undefined, the default response of UIApplication is to terminate its session.

Listing Six shows how the delegate method might be implemented. Here, the method sends a clearFilter message to its data model fooData (line 6). Then it retrieves the top-most view controller and sends a resetView message to that controller (lines 9-11). This assumes, of course, that the controller has a valid resetView method.

Listing Six

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)anApp
{
	UIViewController *tTop;
	
	// clear the filter cache
	[self.fooData clearFilter];
	
	// reset the active view controller
	tTop = self.navigationController.topViewController;
	if (tTop != nil)
		[tTop resetView];
}

Another way to trap a low-memory warning is with the method didReceiveMemoryWarning. This one is an instance method, declared and defined by the UIViewController class. Its default response is to dispose of the view handled by that controller.

Listing Seven shows how didReceiveMemoryWarning might be overridden. The method just sends the same resetView message to the controller itself (line 4). But unlike the UIApplication delegate method, this one gets invoked for every controller present in the view stack.

Listing Seven

- (void)didReceiveMemoryWarning
{
	// reset the active view
	[self resetView];
}

The iPhone simulator can easily simulate a low-memory state. With it, we can test code written to respond to that state. To prepare the Xcode project, first make sure the simulator is the target device. Near the top-left corner of the project window, click the "Overview" pop-up menu and choose the menu item "Simulator." Also, from the same menu, choose the menu item "Debug" to enable the source-level debugger.

Next, place a breakpoint on any of the low-memory traps described above. Rebuild the project by choosing "Build" from the Xcode "Build" menu. Then choose "Debug" from the "Run" menu to start a debug session.

Xcode will start up the simulator, load in the executable, and launch it afterwards. Once the app's main window appears, click the simulator's "Hardware" menu and choose "Simulate Memory Warning." This will cause the simulator to generate a low-memory signal. If all goes well, Xcode will come up front and highlight one of the breakpoints. To bring up the source-level debugger, choose "Debugger" from the Xcode "Run" menu.

Conclusion

Proper memory management is essential for a stable, well-behaved iOS application. The application must be frugal with its memory use, and it must know how to react in a low-memory situation.

In this article, we studied the lifecycle of a typical Cocoa object. We learned how iOS differs from its OS X cousin in terms of memory support. We reviewed guidelines on how to reduce our application's memory footprint, and on how to manage its limited memory. And we studied how to trap a low-memory signal, as well as test the trap on the iPhone simulator.

References

Apple Developer Connection. How Memory Management Works. Cocoa Fundamentals Guide. Apple Inc. December 2010.

Apple Developer Connection. Practical Memory Management. Memory Management Programming Guide. Apple Inc. December 2010.

Apple Developer Connection. Tips for Allocating Memory. Memory Usage Performance Guide. Apple Inc. July 2008. pp. 15-23.

Apple Developer Connection. Use Memory Efficiently. iOS Application Programming Guide. Apple Inc. December 2010. pp. 15-23.

Robert Clair. VTM Seattle. iPhone OS Memory Management. Seattle, WA. April 25, 2010.

Joel Ivory Johnson. Getting Started with iPhone and iOS Development. June 21, 2010.

Stephen Kochan. ClassroomM, Inc. Really, Really Understanding Memory Management. October 17, 2010.

Brent Simmons. How I Manage Memory. June 28, 2010.


José R.C. Cruz is an engineering writer who frequently writes about iOS for Dr. Dobb's. He resides in North Vancouver, British Columbia.

Related Articles

Generating Code Metrics and Estimating Costs with Xcode

How to Secure and Authenticate Images Using Watermarks

Cocoa Memory Management (2006)


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video