How to convert a mutable array to an immutable array

[snippets_intro text=”to convert a mutable array to an immutable array”]

When you want to convert a mutable array to an immutable array, try this:

// Converting from a mutable array to its immutable counterpart:
NSMutableArray *myMutableArray = methodToReturnAnNSMutableArray();
NSArray *myArray = myMutableArray;

Converting a mutable to an immutable array is much simpler than the reverse process because all NSMutable* classes inherit from their immutable counterparts. However, if you no longer need the ability to add and remove elements from a NSMutableArray the best way is to make an immutable copy of the original, and then release that original. Reasons:

  1. The container only stores references to objects, so the copy operation never copies the actual objects, just references to them.
  2. It’s much faster to access items from an array than from a linked list.
  3. The resultant NSArray will take up less memory than the NSMutableArray just released.
// Stripping off the additional functionality of a mutable container for efficiency.
NSMutableArray *myMutableArray = methodToReturnAnNSMutableArray();
NSArray *myArray = [myMutableArray copy];
[myMutableArray release];

Leave a Reply

Your email address will not be published. Required fields are marked *