< Previous PageNext Page > Hide TOC

Arrays: Ordered Collections

Arrays are ordered collections of objects. Cocoa provides several array classes, NSArray, NSMutableArray (a subclass of NSArray), and NSPointerArray.

Contents:

Array Fundamentals
Mutable Arrays
Using Arrays


Array Fundamentals

Arrays are ordered collections that can contain any sort of object—the collection does not have to be homogeneous. For example, an array could contain any combination of Cat and Dog objects, and if it’s mutable you could add a Vet object, but it could not contain an int or a float. NSPointerArray differs from NSArray and NSMutableArray in that the former can contain nil values (if you need to add a representation of a null value to an instance of NSArray, use NSNull) and its contents do not need to be objects; moreover, it also offers memory management options using an instance of NSPointerFunctions.

An NSArray object manages a static array—that is, once you have created the array you cannot add objects to it or remove objects from it—you can, however, modify individual elements themselves (if they support modification). For example, given an NSArray object that contains just a single Dog object, you could not add another Dog, or a Cat. You could, however, change the Dog’s name.

An NSMutableArray object manages a dynamic—or mutable—array, which allows the addition and deletion of entries at any time, automatically allocating memory as needed. For example, given an NSMutableArray object that contains just a single Dog object, you can add another Dog, or a Cat, or any other object. You also, as with an NSArray instance, change the Dog’s name—and in general, anything that you can do with an NSArray object you can do with an NSMutableArray object.

You can easily create an instance of one type of array from the other using the initializer initWithArray: or the convenience constructor arrayWithArray:. For example, if you have an instance of NSArray, myArray, you can create a mutable copy as follows:

NSMutableArray *myMutableArray = [NSMutableArray arrayWithArray:myArray];

In general, you instantiate an array by sending one of the array... messages to either the NSArray or NSMutableArray class object. The array... messages return an array containing the elements you pass in as arguments. And when you add an object to an Objective-C array, the object isn’t copied, but rather receives a retain message before its id is added to the array. When an array is deallocated, each element is sent a release message.

NSArray’s two primitive methods—count and objectAtIndex—provide the basis for all other methods in its interface. The count method returns the number of elements in the array. objectAtIndex gives you access to the array elements by index, with index values starting at 0.

Mutable Arrays

NSMutableArray’s primitive methods, listed below, provide the basis for its ability to add, replace, and remove elements:

The other methods in NSMutableArray provide convenient ways of inserting an object into a specific slot in the array and removing an object based on its identity or position in the array, as illustrated in the following example.

NSMutableArray *array = [NSMutableArray array];
[array addObject:[NSColor blackColor]];
[array insertObject:[NSColor redColor] atIndex:0];
[array insertObject:[NSColor blueColor] atIndex:1];
[array addObject:[NSColor whiteColor]];
[array removeObjectsInRange:(NSMakeRange(1, 2))];
// array now contains redColor and whiteColor

In a managed memory environment, when an object is removed from a mutable array it receives a release message. This means that if an array is the only owner of an object, then (by standard rules of memory management) the object is deallocated when it is removed. If you want to use the object after its removal, you should therefore typically send it a retain message before it’s removed from the array. For example, if in the following example anArray is the only owner of anObject, the third statement below would result in a run-time error:

id anObject = [anArray objectAtIndex:0];
[anArray removeObjectAtIndex:0];
// if no object other than anArray owned anObject, the next line causes a crash
[anObject someMessage];

If you want to use an object after removing it from an array, you should retain it first as shown in the following example:

id anObject = [[anArray objectAtIndex:0] retain];
[anArray removeObjectAtIndex:0];
[anObject someMessage];
// remember to send anObject a release message when you have finished with it

Using Arrays

The NSArray methods objectEnumerator and reverseObjectEnumerator grant sequential access to the elements of the array, differing only in the direction of travel through the elements (see “Enumerators: Traversing a Collection’s Elements”). NSArray’s makeObjectsPerformSelector: and makeObjectsPerformSelector:withObject: methods let you send messages to all objects in the array.

You can extract a subset of the array (subarrayWithRange:) or concatenate the elements of an array of NSString objects into a single string (componentsJoinedByString:). In addition, you can compare two arrays using the isEqualToArray: and firstObjectCommonWithArray: methods. Finally, you can create a new array that contains the objects in an existing array and one or more additional objects with arrayByAddingObject: or arrayByAddingObjectsFromArray:.

There are two principal methods you can use to determine whether an object is present in an array, indexOfObject: andindexOfObjectIdenticalTo:—there are also two variants, indexOfObject:inRange: and indexOfObjectIdenticalTo:inRange: that you can use to search a range within an array. The indexOfObject: methods test for equality by sending elements in the array an isEqual: message; the indexOfObjectIdenticalTo: methods test for equality using pointer comparison. The difference is illustrated in the following example:

NSString *yes0 = @"yes";
NSString *yes1 = @"YES";
NSString *yes2 = [NSString stringWithFormat:@"%@", yes1];
 
NSArray *yesArray = [NSArray arrayWithObjects: yes0, yes1, yes2, nil];
 
NSUInteger index;
 
index = [yesArray indexOfObject:yes2];
// index is 1
 
index = [yesArray indexOfObjectIdenticalTo:yes2];
// index is 2


< Previous PageNext Page > Hide TOC


© 2009 Apple Inc. All Rights Reserved. (Last updated: 2009-02-04)


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.