Archive for January, 2009

Tips for the C# Coder: ArrayList != NSArray

January 26, 2009

One of my favorite collection containers in .NET (1.1) was the ArrayList. Then .NET 2.0 came around and generic lists were introduced i.e. the List<T> class. Man was I impressed.

Enter the iPhone SDK and Objective-C. I quickly learned that things were slightly different.

When coding for the iPhone SDK, you are provided with two classes that are similar to our trusted little collection friends. These are the NSArray and its counter part, the NSMutableArray.

The NSArray provides all the low level fun features that you’d expect in a collection class. However, once you have created an instance of the NSArray you cannot add or remove objects. This is where the NSMutableArray comes in.

The NSMutableArray is a sub-class of the NSArray. It provides the functionality to modify the collection once the instance has been created. With the NSMutableArray, you can add, insert, remove and replace objects from list. Hence the “mutable” in the name.


NSArray: you can’t change the collection once the collection has been created.

NSMutableArray: you can modify the collection after the collection has been created.


  1. To quickly create an array that “behaves” like an ArrayList or List<T> collection, use a NSMutableArray.
  2. To initialize a NSMutableArray, do this:

    NSMutableArray *array = [[NSMutableArray alloc] init];

  3. To create a new NSMutableArray from an existing array, do this:

    NSMutableArray *array = [[NSMutableArray alloc] initWithArray:someOtherArray];

  4. To add one array to an existing array (that may or may not already have data), do this:

    [oldArray addObjectsFromArray:newArray];

  5. To add a single object to a NSMutableArray:

    [oldArray addObject:yourNewObject];

  6. To delete all the objects of a NSMutableArray, do this:

    [oldArray removeAllObjects];

Let me know if this helps. Drop me a comment or ping me on twitter



Objective-C heads up for C# developers

January 22, 2009

iPhone UITableView events bubble down instead of up.

Take for instance the a program that has a UITableViewController_A, that nests UITableViewController_B. Tapping on a cell that is in the child (ie UITableViewController_B), fires the tableView:didSelectRowAtIndexPath of A, then B.