Memory management

Memory management is the programming discipline of managing the life cycles of objects and freeing them when they are no longer needed. Managing object memory is a matter of performance; if an application doesn’t free unneeded objects, its memory footprint grows and performance suffers. Memory management in a Cocoa application that doesn’t use garbage collection is based on a reference counting model. When you create or copy an object, its retain count is 1. Thereafter other objects may express an ownership interest in your object, which increments its retain count. The owners of an object may also relinquish their ownership interest in it, which decrements the retain count. When the retain count becomes zero, the object is deallocated (destroyed).

To assist you in memory management, Objective-C gives you methods and mechanisms that you must use in conformance with a set of rules.

Note: In Mac OS X, you can either explicitly manage memory or use the garbage collection feature of Objective-C. Garbage collection is not available in iOS.

Memory management

Memory-Management Rules

Memory-management rules, sometimes referred to as the ownership policy, help you to explicitly manage memory in Objective-C code.

If you receive an object from elsewhere in your program, it is normally guaranteed to remain valid within the method or function it was received in. If you want it to remain valid beyond that scope, you should retain or copy it. If you try to release an object that has already been deallocated, your program crashes.

Aspects of Memory Management

The following concepts are essential to understanding and properly managing object memory:

Prerequisite Articles

Related Articles

Did this document help you? Yes It's good, but... Not helpful...


Last updated: 2010-08-03