User Tools

Site Tools


Memory Management

Objects created in any language require memory to live in. The process of managing this space is called Memory management.

The key issues are as follows:

  1. When and how do you request new memory?
  2. When and how do you give back memory?

Quick vocab (simplified):

  1. allocate- the act of reserving memory of a given size for use. Memory can only be used by the program.
  2. deallocate(or “freeing”)- giving memory back to the operating system. Memory is used at the discretion of the operating system.

These are incredibly important issues that face any language. Example implementations:

  1. Java- called garbage collecting. Routinely traverses all “roots”, walking down each variable reference and marking them alive; any objects not marked alive are removed from memory. Allocation happens implicitly when creating an object.
  2. C- manual allocation, manual freeing, using the methods malloc() and free()
  3. Objective-C- ARC or Automatic Reference Counting. Allocation happens explicitly though alloc method call. Deallocation happens implicitly no objects hold references (pointers, variables) to a given object.

Each Objective-C object has an internal counter that keeps track of how many objects are retaining it by holding a reference to it.

  1. Retain- hold onto an object; increase its retain count by 1
  2. Release- I do not need this object anymore, decrement its retain count by 1

If a retain count hits 0, free the object.

Objective-C used to use MRR, Manual Retain Release, which required you to call retain and release on objects as you manipulated them. Thankfully, ARC autogenerates all retain and release calls from the compiler, removing the need to keep track of reference counts.

The only explicit point where you as a developer must manage memory is with property modifiers, included in parenthesis after @property but before type *name;.

Two modifiers that relate to memory management:

  1. strong- while this property holds a given variable, increase its retain count by one. The object cannot be freed while the property still points to them.
  2. weak- point to the given object, but do not count this reference as retain. If the object's retain count goes to 0, the property will be nilled out.

When in doubt, use strong. This increases the chance that you'll leak memory, but at this level of development it will not ruin your app. Use weak only when you're sure another object has a strong reference to the object.

ios-labs-s14/intermediate-arc.txt · Last modified: 2014/02/23 22:33 by mbarboi