Next Page > Hide TOC

Legacy Documentclose button

Important: The information in this document is obsolete and should not be used for new development.

NSArray

Inherits from
Implements
Package
com.apple.cocoa.foundation
Companion guides

Class at a Glance

An NSArray stores an immutable array of objects. The mutable subclass of NSArray is NSMutableArray.

Principal Attributes

Creation

NSArray Constructors

Returns an array.

Commonly Used Methods

count

Returns the number of objects currently in the array.

objectAtIndex

Returns the object located at the specified index.

Overview

NSArray and its subclass NSMutableArray manage collections of objects called arrays. NSArray creates static arrays, and NSMutableArray creates dynamic arrays.

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.

The methods objectEnumerator and reverseObjectEnumerator also grant sequential access to the elements of the array, differing only in the direction of travel through the elements. These methods are provided so that arrays can be traversed in a manner similar to that used for objects of other collection classes in both the Java API and Foundation, such as java.util.Hashtable or NSDictionary. See the objectEnumerator method description for a code excerpt that shows how to use these methods to access the elements of an array.

NSArray provides methods for querying the elements of the array. The indexOfObjectmethod searches the array for the object that matches its argument. To determine whether the search is successful, each element of the array is sent an equals message. Another method, indexOfIdenticalObject, is provided for the less common case of determining whether a specific object is present in the array. The indexOfIdenticalObject method tests each element in the array to see whether its id matches that of the argument.

NSArray’s filteredArrayUsingPredicate method allows you to create a new array from an existing array filtered using a predicate (see Predicates Programming Guide).

To act on the array as a whole, a variety of other methods are defined. You can extract a subset of the array (subarrayWithRange) or concatenate the elements of an array of Strings into a single string (componentsJoinedByString). In addition, you can compare two arrays using the isEqualToArray and firstObjectCommonWithArray methods. Finally, you can create new arrays that contain the objects in an existing array and one or more additional objects with arrayByAddingObject and arrayByAddingObjectsFromArray.

Subclassing Notes

Most developers would not have any reason to subclass NSArray. The class does well what it is designed to do—maintain an ordered collection of objects. But there are situations where a custom NSArray object might come in handy. Here are a few possibilities:

Methods to Override

Any subclass of NSArray must override the primitive instance methods count and objectAtIndex. These methods must operate on the backing store that you provide for the elements of the collection. For this backing store you can use a static array, a standard NSArray object, or some other data type or mechanism. You may also choose to override, partially or fully, any other NSArray method for which you want to provide an alternative implementation.

You might want to implement an constructor for your subclass that is suited to the backing store that the subclass is managing. The NSArray class adopts the NSCopying, NSMutableCopying, and NSCoding interfaces; if you want instances of your own custom subclass created from copying or coding, override the methods in these interfaces.

Remember that NSArray is the public interface for a class cluster and what this entails for your subclass. The primitive methods of NSArray do not include any designated initializers. This means that you must provide the storage for your subclass and implement the primitive methods that directly act on that storage.

Special Considerations

In most cases your custom NSArray class should conform to Cocoa’s object-ownership conventions. Of course, if the reason for subclassing NSArray is to implement object-retention behavior different from the norm (for example, a non-retaining array), then you can ignore this requirement.

Alternatives to Subclassing

Before making a custom class of NSArray, investigate the corresponding Core Foundation type, CFArray. Because NSArray and CFArray are “toll-free bridged,” you can substitute a CFArray object for a NSArray object in your code (with appropriate casting). Although they are corresponding types, CFArray and NSArray do not have identical interfaces or implementations, and you can sometimes do things with CFArray that you cannot easily do with NSArray. For example, CFArray provides a set of callbacks, some of which are for implementing custom retain-release behavior. If you specify NULL implementations for these callbacks, you can easily get a non-retaining array.

If the behavior you want to add supplements that of the existing class, you could write a category on NSArray. Keep in mind, however, that this category will be in effect for all instances of NSArray that you use, and this might have unintended consequences.

Tasks

Constructors

Querying the Array

Comparing Arrays

Deriving New Arrays

Sorting Arrays

Working with String Elements

Constructors

NSArray

public NSArray()

Discussion

Creates an empty array. This method is used by mutable subclasses of NSArray.

public NSArray(Object anObject)

Discussion

Creates an array containing the single element anObject. After an immutable array has been initialized in this way, it can’t be modified.

public NSArray(Object[] objects)

Discussion

Creates an array containing objects. After an immutable array has been initialized in this way, it can’t be modified.

public NSArray(NSArray anArray)

Discussion

Creates an array containing the objects in anArray. After an immutable array has been initialized in this way, it can’t be modified.

Static Methods

componentsSeparatedByString

Returns an NSArray containing substrings from aString that have been divided by separator.

public static NSArray componentsSeparatedByString(String aString, String separator)

Discussion

The substrings in the array appear in the order they did in aString. If aString begins or ends with the separator, the first or last substring, respectively, is empty. For example, this code excerpt:

NSStringReference list = "wrenches, hammers, saws";
NSArray listItems = [list.componentsSeparatedByString (", ")];

produces an array with these contents:

Index

Substring

0

wrenches

1

hammers

2

saws

If list begins with a comma and space—for example, “, wrenches, hammers, saws”—the array has these contents:

Index

Substring

0

(empty string)

1

wrenches

2

hammers

3

saws

If list has no separators—for example, “wrenches”—the array contains the string itself, in this case “wrenches”.

See Also

Instance Methods

arrayByAddingObject

Returns a new array that is a copy of the receiver with anObject added to the end.

public NSArray arrayByAddingObject(Object anObject)

Discussion

If anObject is null, an InvalidArgumentException is thrown.

See Also

arrayByAddingObjectsFromArray

Returns a new array that is a copy of the receiver with the objects contained in otherArray added to the end.

public NSArray arrayByAddingObjectsFromArray(NSArray otherArray)

See Also

componentsJoinedByString

Constructs and returns a String that is the result of interposing separator between the elements of the receiver’s array.

public String componentsJoinedByString(String separator)

Discussion

For example, this code excerpt writes the path System/Library to the console:

NSArray pathArray = new NSArray(new Object[] {"System",
    "Library"});
System.out.println("The path is "+
    pathArray.componentsJoinedByString("/") + ".");
 

Each element in the receiver’s array must handle either description, or if it is not implemented, toString. If the receiver has no elements, a String representing an empty string is returned.

See Also

containsObject

Returns true if anObject is present in the array.

public boolean containsObject(Object anObject)

Discussion

This method determines whether an object is present in the array by sending an equals message to each of the array’s objects (and passing anObject as the parameter to each equals message).

See Also

count

Returns the number of objects currently in the array.

public int count()

See Also

filteredArrayUsingPredicate

Evaluates the predicate against the receiver’s content and returns a new array containing the objects that match.

public NSArray filteredArrayUsingPredicate(NSPredicate predicate)

Discussion

For more details, see Predicates Programming Guide.

Availability

firstObjectCommonWithArray

Returns the first object contained in the receiver that’s equal to an object in otherArray.

public Object firstObjectCommonWithArray(NSArray otherArray)

Discussion

If no such object is found, this method returns null. This method uses equals to check for object equality.

See Also

getObjects

Copies all objects contained in the receiver to aBuffer.

public void getObjects(Object[] aBuffer)

Copies the objects contained in the receiver that fall within the specified range to aBuffer.

public void getObjects(Object[] aBuffer, NSRange aRange)

indexOfIdenticalObject

This method has been deprecated.

public int indexOfIdenticalObject(Object anObject)

This method has been deprecated.

public int indexOfIdenticalObject(Object anObject, NSRange aRange)

See Also

indexOfObject

Searches all objects in the receiver for anObject and returns the lowest index whose corresponding array value is equal to anObject.

public int indexOfObject(Object anObject)

Discussion

Objects are considered equal if equals returns true. If none of the specified objects is equal to anObject, returns NSArray.NotFound.

Searches the specified range within the receiver for anObject and returns the lowest index whose corresponding array value is equal to anObject.

public int indexOfObject(Object anObject, NSRange aRange)

Discussion

Objects are considered equal if equals returns true. If none of the specified objects is equal to anObject, returns NSArray.NotFound.

See Also

isEqualToArray

Compares the receiving array to otherArray.

public boolean isEqualToArray(NSArray otherArray)

Discussion

If the contents of otherArray are equal to the contents of the receiver, this method returns true. If not, it returns false.

Two arrays have equal contents if they each hold the same number of objects and objects at a given index in each array satisfy the equals test.

lastObject

Returns the object in the array with the highest index value.

public Object lastObject()

Discussion

If the array is empty, lastObject returns null.

See Also

objectAtIndex

Returns the object located at index.

public Object objectAtIndex(int index)

Discussion

If index is beyond the end of the array (that is, if index is greater than or equal to the value returned by count), a RangeException is thrown.

See Also

objectEnumerator

public java.util.Enumeration objectEnumerator()

Discussion

Returns an enumerator object that lets you access each object in the receiver, in order, starting with the element at index 0, as in:

java.util.Enumeration enumerator = myArray.objectEnumerator();
 
while (enumerator.hasMoreElements()) {{
    Object anObject = enumerator.nextElement();
    /* code to act on each element */
}

When this method is used with mutable subclasses of NSArray, your code shouldn’t modify the array during enumeration.

See Also

objectsAtIndexes

Returns an array containing the objects in the receiver at the specified indexes.

public NSArray objectsAtIndexes(NSIndexSet indexes)

Discussion

Throws an exception if any location in indexes exceeds the bounds of the receiver.

Availability
See Also

reverseObjectEnumerator

Returns an enumerator object that lets you access each object in the receiver, in order, from the element at the highest index down to the element at index 0.

public java.util.Enumeration reverseObjectEnumerator()

Discussion

Your code shouldn’t modify the array during enumeration.

See Also

sortedArrayUsingDescriptors

Returns a copy of the receiver sorted as specified by sortDescriptors.

public NSArray sortedArrayUsingDescriptors(NSArray sortDescriptors)

Discussion

The first descriptor specifies the primary key value path to be used in sorting the receiver’s contents. Any subsequent descriptors are used to further refine sorting of objects with duplicate values. See NSSortDescriptor for additional information.

Availability
See Also

sortedArrayUsingSelector

Returns an array that lists the receiver’s elements in ascending order, as determined by the comparison method specified by the selector selector.

public NSArray sortedArrayUsingSelector(NSSelector selector)

Discussion

The new array contains references to the receiver’s elements, not copies of them. The retain count is incremented for each element in the receiving array.

The selector message is sent to each object in the array and has as its single argument another object in the array. The selector method is used to compare two elements at a time and should return OrderedAscending if the receiver is smaller than the argument, OrderedDescending if the receiver is larger than the argument, and OrderedSame if they are equal.

See Also

subarrayWithRange

Returns a new array containing the receiver’s elements that fall within the limits specified by range.

public NSArray subarrayWithRange(NSRange range)

Discussion

If range isn’t within the receiver’s range of elements, a RangeException is thrown.

For example, the following code example creates an array containing the elements found in the first half of wholeArray (assuming wholeArray exists).

NSRange theRange = new NSRange(0, wholeArray.count()/2);
NSArray halfArray = wholeArray.subarrayWithRange(theRange);

Constants

NSArray provides the following constant as a convenience; you can use it to compare to values returned by some NSArray methods:

Constant

Description

NotFound

Returned when an object is not found in an NSArray.



Next Page > Hide TOC


© 1997, 2006 Apple Computer, Inc. All Rights Reserved. (Last updated: 2006-07-24)


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.