Working with Objective-C Array Objects
Previous | Table of Contents | Next |
Understanding Objective-C Number Objects | Objective-C Dictionary Objects |
Purchase the full edition of this Objective-C book in Print ($14.99) or eBook ($12.99) format Objective-C 2.0 Essentials Print and eBook (ePub/PDF/Kindle) editions contain 31 chapters. |
An array is an object that contains collections of other objects. Array objects in Objective-C are handled using the 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 programming 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", nil];
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:
NSArray *myColors; myColors = [NSArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil]; NSLog (@"Number of elements in array = %lu", [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
Accessing Array Elements using Fast Enumeration
The technique for accessing all the array elements using a for loop as described in the previous section is a little ungainly. Another, easier mechanism for accessing element in an array involves something called fast enumeration. Fast enumeration simply requires that a variable be declared to hold each array element, and then referenced in the for loop:
NSArray *myColors; NSString *color; myColors = [NSArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil]; for (color in myColors) NSLog (@"Element = %@", color);
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 also 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 be 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 positions:
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. A 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 removeLastObject];
Sorting Array Objects
The Foundation Framework NSArray class, and the subclasses thereof, provide a number of mechanisms for sorting 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.
Purchase the full edition of this Objective-C book in Print ($14.99) or eBook ($12.99) format Objective-C 2.0 Essentials Print and eBook (ePub/PDF/Kindle) editions contain 31 chapters. |
Previous | Table of Contents | Next |
Understanding Objective-C Number Objects | Objective-C Dictionary Objects |