Arrays in Objective-C do not contain the objects that belong to it, they hold a pointer (reference) to each object in the array.  So when you use :addObject you are simply storing the address of that object inside the array. This means that you can have different types in a single array.  This is a key difference to other languages where an array can only hold 1 object type.

NSArray

A NSArray is 'immutable' – you can't add or remove objects (alter the array structure) after the array is created.


	NSArray *options = @[@"Option 1", @"Option 2"];
	NSArray *options = @[@0.5f, @1, @1.5, @2, @2.5, @3, @3.5, @4, @4.5, @5];

NSMutableArray

A NSMutableArray allows you to add and remove objects dynamically (i.e. alter the array structure after the array is created).


	NSMutableArray *items = [[NSMutableArray alloc] init];
	[items addObject:@"One"];		//Add to end of array
	[items addObject:@"Two"];		//Add to end of array
	[items insertObject:@"Zero" atIndex:0];

	[items release];		//Remember to release an array when done with it

Nil(Null) Array Entry

You must use the NSNull object (NSNull is an object that represents nil), e.g.

	[array addObject:[NSNull null]];

Read Array Entry


	NSString *object = [array objectAtIndex:0];

Write New Array Entry


	[SomeArrayName insertObject:SomeObjectName atIndex:12];

	[SomeArrayName addObject:SomeObjectName];	    //Insert at end

Overwrite Array Entry


	[MyArrayName replaceObjectAtIndex:5 withObject:MyNewObject];

Edit Object In An Array

Say you've created an array of objects based on your own custom class, like this:


    MyClass *MyClass1 = [[MyClass alloc] init];
    [MyArray addObject:MyClass1];
    [MyClass1 release];

If you want to edit one of the objects in the array this is what you do:


    MyClass *MyClass1 = [MyClass objectAtIndex:([MyArray count] - 1)];
    MyClass1.MyParameterInTheClass = @"A new string value";

MyClass1 is not a newly created object or a copy of the object in the array, it is a pointer to the same object contained in the array. Therefore anything you do to it is actually being done to the object in the array.
There is no need to release MyClass1 as it was never allocated, it's just a pointer to an object which was allocated when it was first created.

Remove Entry From Array


	[SomeArrayName removeObjectAtIndex:5];

Array Length


	int NumberOfObjects = [SomeArrayName count];

	//or
	if (SomeIndexVariable == [SomeArrayName count])
		SomeIndexVariable = 0;

Clear Array


	[SomeArrayName removeAllObjects];

Arrays Of Integers etc

You need to turn the integer into an object, e.g.


    //To store it
    [SomeArrayName addObject:[NSNumber numberWithInteger:5]];

    //To turn is back when reading it
    int sum = [[SomeArrayName objectAtIndex:0] intValue]

Comments