Working with Objective-C Array Objects
Revision as of 21:05, 1 February 2016 by Neil (Talk | contribs) (Text replacement - "<google>BUY_OBJC</google>" to "<htmlet>objc<htmlet>")
Previous | Table of Contents | Next |
Understanding Objective-C Number Objects | Objective-C Dictionary Objects |
Cannot find HTML file objc<htmlet>
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:
<pre>
NSArray *myColors;
myColors = [NSArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];
<pre>
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:
<pre>
NSMutableArray *myColors;
myColors = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];
<pre>
== 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:
<pre>
NSArray *myColors;
myColors = [NSArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];
NSLog (@"Number of elements in array = %lu", [myColors count]);
<pre>
When executed, the above code will output the following:
<pre>
Number of elements in array = 4
<pre>
== 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:
<pre>
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]);
<pre>
When run, the above code will display each element in the array object:
<pre>
Element 0 = Red
Element 1 = Green
Element 2 = Blue
Element 3 = Yellow
<pre>
== 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:
<pre>
NSArray *myColors;
NSString *color;
myColors = [NSArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];
for (color in myColors)
NSLog (@"Element = %@", color);
<pre>
== 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:
<pre>
NSMutableArray *myColors;
myColors = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];
[myColors addObject: @"Indigo"];
[myColors addObject: @"Violet"];
<pre>
== 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:
<pre>
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]);
<pre>
When we compile and run the code, the following output confirms that the new objects were indeed inserted at the specified index positions:
<pre>
Element 0 = Red
Element 1 = Indigo
Element 2 = Green
Element 3 = Violet
Element 4 = Blue
Element 5 = Yellow
<pre>
== 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:
<pre>
myColors = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];
[myColors removeObjectAtIndex: 0];
<pre>
To remove the first instance of a specific object from an array use ''removeObject'':
<pre>
myColors = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];
[myColors removeObject: @"Red"];
<pre>
To remove all instances of a specific object in an array, use ''removeObjectIdenticalTo'':
<pre>
myColors = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", @"Red", @"Red", nil];
[myColors removeObjectIdenticalTo: @"Red"];
<pre>
To remove all objects from an array, use ''removeAllObjects'':
<pre>
myColors = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];
[myColors removeAllObjects];
<pre>
To remove the last object in the array, use the ''removeLastObject'' method:
<pre>
myColors = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];
[myColors removeLastObject];
<pre>
== 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:
<pre>
NSMutableArray *myColors = [NSMutableArray arrayWithObjects: @"red", @"green", @"blue", @"yellow", nil];
NSArray *sortedArray;
sortedArray = [myColors sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
<pre>
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.
<google>BUY_OBJC_BOTTOM<google>
<hr>
<table border="0" cellspacing="0" width="100%">
<tr>
<td width="20%">[[Understanding Objective-C Number Objects|Previous]]<td align="center">[[Objective-C 2.0 Essentials|Table of Contents]]<td width="20%" align="right">[[Objective-C Dictionary Objects|Next]]<td>
<tr>
<td width="20%">Understanding Objective-C Number Objects<td align="center"><td width="20%" align="right">Objective-C Dictionary Objects<td>
<table>.html