Working with Objective-C Array Objects

Revision as of 17:11, 9 November 2009 by Neil (Talk | contribs) (Sorting Array Objects)

Revision as of 17:11, 9 November 2009 by Neil (Talk | contribs) (Sorting Array Objects)

An array is an object that contains collections of other objects. Array objects in Objective-C are handled using Foundation Framework NSArray class. The NSArray class contains a number of methods specifically designed to ease the creation and manipulation of arrays within Objective-C programs. Unlike some object oriented programing languages (C# being one example), the objects contained in an array do not all have to be of the same type.

In this chapter, we will cover some of the basics of working with array objects in Objective-C. Many more class and instance methods are provided by the array classes than can be covered here so refer to the Foundation Framework documentation for a full listing of capabilities.

Mutable and Immutable Arrays

Array objects in Objective-C come in mutable and immutable forms. The contents of immutable arrays cannot be changed after the array has been initialized. Immutable arrays are instantiated from the NSArray class. Mutable arrays are created using the NSMutableArray class (a subclass of NSArray) and can be modified after they have been created and initialized.

Creating an Array Object

The NSArray class contains a class method named arrayWithObjects that can be called upon to create a new array object and initialize it with elements. For example:

NSArray *myColors;

myColors = [NSArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];

The above code creates a new array object called myColors and initializes it with four constant string objects containing the strings "Red", "Green", "Blue" and "Yellow". A nil entry is required so that the methods called upon to work on the array know where the end of the array is located. Failure to include this entry may result in the application crashing, particularly during sort operations.

Because we used the NSArray class in the above example the contents of the array object cannot be changed subsequent to initialization. To create a mutable array that will allow the array contents to be modified, we need to use the NSMutableArray class:

NSMutableArray *myColors;

myColors = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow"];

Finding out the Number of Elements in an Array

The number of objects in an array (referred to as elements) can be identified using the count instance method of the NSArray class:

        
myColors = [NSArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];

NSLog (@"Number of elements in array = %i", [myColors count]);

When executed, the above code will output the following:

Number of elements in array = 4

Accessing the Elements of an Array object

The objects contained in an array are given index positions beginning at position zero. Each element may be accessed by passing the required index position through as an argument to the NSArray objectAtIndex instance method. We can, therefore, now extend our array example to display each element, using the count method to identify in advance how many elements there are to display:

NSArray *myColors;
int i;
int count;

myColors = [NSArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];
count = [myColors count];

for (i = 0; i < count; i++)
        NSLog (@"Element %i = %@", i, [myColors objectAtIndex: i]);

When run, the above code will display each element in the array object:

Element 0 = Red
Element 1 = Green
Element 2 = Blue
Element 3 = Yellow

Adding Elements to an Array Object

New elements may be added to a mutable array object using the addObject instance method of the NSMutableArray class. For example, to declare and initialize an array, and then later add new element object the following code might be used:

NSMutableArray *myColors;

myColors = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];

[myColors addObject: @"Indigo"];
[myColors addObject: @"Violet"];

Inserting Elements into an Array

The previous method appends new objects onto the end of an array. It is alos possible to insert new objects at specific index points in an array object using the insertObject instance method. This method accepts as arguments the object to me inserted and the index position at which the insertion is to take place:

NSMutableArray *myColors;
int i;
int count;

myColors = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];

[myColors insertObject: @"Indigo" atIndex: 1];
[myColors insertObject: @"Violet" atIndex: 3];

count = [myColors count]; 

for (i = 0; i < count; i++)
        NSLog (@"Element %i = %@", i, [myColors objectAtIndex: i]);

When we compile and run the code, the following output confirms that the new objects were indeed inserted at the specified index postions:

Element 0 = Red
Element 1 = Indigo
Element 2 = Green
Element 3 = Violet
Element 4 = Blue
Element 5 = Yellow

Deleting Elements from an Array Object

The NSMutableArray class provides a number of instance methods designed specifically to remove one or more elements from an array object. As sample of some of the more commonly used methods is provided below. This list is not exhaustive so refer to the Foundation Framework documentation for the NSMutableArray class for a full listing.

To remove an element at a specific index location, use the removeObjectAtIndex method:

myColors = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];

[myColors removeObjectAtIndex: 0];

To remove the first instance of a specific object from an array use removeObject:

myColors = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];

[myColors removeObject: @"Red"];

To remove all instances of a specific object in an array, use removeObjectIdenticalTo:

myColors = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", @"Red", @"Red", nil];

[myColors removeObjectIdenticalTo: @"Red"];

To remove all objects from an array, use removeAllObjects:

myColors = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];

[myColors removeAllObjects];

To remove the last object in the array, use the removeLastObject method:

myColors = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];

[myColors removeLastObjects];

Sorting Array Objects

The Foundation Framework NSArray class, and the subclasses thereof, provide a number of mechanisms for sorting the the elements of an array into a specific order. The simplest way to achieve this is to use the sortedArrayUsingSelector instance method. For example, to perform a sort on our example array using this method, we could use the following code:

NSMutableArray *myColors = [NSMutableArray arrayWithObjects: @"red", @"green", @"blue", @"yellow", nil];

NSArray *sortedArray;

sortedArray = [myColors sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

As we can see from the above example, the method returns a new array containing the elements of the original array sorted using the localizedCaseInsensitiveCompare method. In practice any method can be used in this context as long as that method is able to compare two objects and return an NSOrderedAscending, NSOrderedSame or NSOrderedDescending result.