Class

NSArray

A static ordered collection of objects.

Declaration

@interface NSArray<__covariant ObjectType> : NSObject

Overview

NSArray and its subclass NSMutableArray manage ordered collections of objects called arrays. NSArray creates static arrays, and NSMutableArray creates dynamic arrays. You can use arrays when you need an ordered collection of objects.

NSArray is “toll-free bridged” with its Core Foundation counterpart, CFArrayRef. See Toll-Free Bridging for more information on toll-free bridging.

Creating NSArray Objects Using Array Literals

In addition to the provided initializers, such as initWithObjects:, you can create an NSArray object using an array literal.

NSArray *array = @[someObject, @"Hello, World!", @42];

In Objective-C, the compiler generates code that makes an underlying call to the arrayWithObjects:count: method.

id objects[] = { someObject, @"Hello, World!", @42 };
NSUInteger count = sizeof(objects) / sizeof(id);
NSArray *array = [NSArray arrayWithObjects:objects
                                     count:count];

You should not terminate the list of objects with nil when using this literal syntax, and in fact nil is an invalid value. For more information about object literals in Objective-C, see Working with Objects in Programming with Objective-C.

In Swift, the NSArray class conforms to the ArrayLiteralConvertible protocol, which allows it to be initialized with array literals. For more information about object literals in Swift, see Literal Expression in The Swift Programming Language (Swift 4.1).

Accessing Values Using Subscripting

In addition to the provided instance methods, such as objectAtIndex:, you can access NSArray values by their indexes using subscripting.

id value = array[3];

Subclassing Notes

There is typically little 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:

  • Changing how NSArray stores the elements of its collection. You might do this for performance reasons or for better compatibility with legacy code.

  • Acquiring more information about what is happening to the collection (for example, statistics gathering).

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 initializer for your subclass that is suited to the backing store that the subclass is managing. If you do, your initializer must invoke one of the designated initializers of the NSArray class, either init or initWithObjects:count:. The NSArray class adopts the NSCopying, NSMutableCopying, and NSCoding protocols; custom subclasses of NSArray should override the methods in these protocols as necessary.

Remember that NSArray is the public interface for a class cluster and what this entails for your subclass. You must provide the storage for your subclass and implement the primitive methods that directly act on that storage.

Alternatives to Subclassing

Before making a custom subclass of NSArray, investigate NSPointerArray and 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. Alternatively, you could use composition to achieve the desired behavior.

Topics

Creating an Array

array

Creates and returns an empty array.

arrayWithArray:

Creates and returns an array containing the objects in another given array.

arrayWithContentsOfFile:

Creates and returns an array containing the contents of the file specified by a given path.

Deprecated
arrayWithContentsOfURL:

Creates and returns an array containing the contents specified by a given URL.

Deprecated
arrayWithObject:

Creates and returns an array containing a given object.

arrayWithObjects:

Creates and returns an array containing the objects in the argument list.

arrayWithObjects:count:

Creates and returns an array that includes a given number of objects from a given C array.

Initializing an Array

init

Initializes a newly allocated array.

initWithArray:

Initializes a newly allocated array by placing in it the objects contained in a given array.

initWithArray:copyItems:

Initializes a newly allocated array using anArray as the source of data objects for the array.

initWithContentsOfFile:

Initializes a newly allocated array with the contents of the file specified by a given path.

Deprecated
initWithContentsOfURL:

Initializes a newly allocated array with the contents of the location specified by a given URL.

Deprecated
initWithObjects:

Initializes a newly allocated array by placing in it the objects in the argument list.

initWithObjects:count:

Initializes a newly allocated array to include a given number of objects from a given C array.

Querying an Array

containsObject:

Returns a Boolean value that indicates whether a given object is present in the array.

count

The number of objects in the array.

getObjects:

Copies all the objects contained in the array to aBuffer.

Deprecated
getObjects:range:

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

firstObject

The first object in the array.

lastObject

The last object in the array.

objectAtIndex:

Returns the object located at the specified index.

objectAtIndexedSubscript:

Returns the object at the specified index.

objectsAtIndexes:

Returns an array containing the objects in the array at the indexes specified by a given index set.

objectEnumerator

Returns an enumerator object that lets you access each object in the array.

reverseObjectEnumerator

Returns an enumerator object that lets you access each object in the array, in reverse order.

Finding Objects in an Array

indexOfObject:

Returns the lowest index whose corresponding array value is equal to a given object.

indexOfObject:inRange:

Returns the lowest index within a specified range whose corresponding array value is equal to a given object .

indexOfObjectIdenticalTo:

Returns the lowest index whose corresponding array value is identical to a given object.

indexOfObjectIdenticalTo:inRange:

Returns the lowest index within a specified range whose corresponding array value is equal to a given object .

indexOfObjectPassingTest:

Returns the index of the first object in the array that passes a test in a given block.

indexOfObjectWithOptions:passingTest:

Returns the index of an object in the array that passes a test in a given block for a given set of enumeration options.

indexOfObjectAtIndexes:options:passingTest:

Returns the index, from a given set of indexes, of the first object in the array that passes a test in a given block for a given set of enumeration options.

indexesOfObjectsPassingTest:

Returns the indexes of objects in the array that pass a test in a given block.

indexesOfObjectsWithOptions:passingTest:

Returns the indexes of objects in the array that pass a test in a given block for a given set of enumeration options.

indexesOfObjectsAtIndexes:options:passingTest:

Returns the indexes, from a given set of indexes, of objects in the array that pass a test in a given block for a given set of enumeration options.

indexOfObject:inSortedRange:options:usingComparator:

Returns the index, within a specified range, of an object compared with elements in the array using a given NSComparator block.

Sending Messages to Elements

makeObjectsPerformSelector:

Sends to each object in the array the message identified by a given selector, starting with the first object and continuing through the array to the last object.

makeObjectsPerformSelector:withObject:

Sends the aSelector message to each object in the array, starting with the first object and continuing through the array to the last object.

enumerateObjectsUsingBlock:

Executes a given block using each object in the array, starting with the first object and continuing through the array to the last object.

enumerateObjectsWithOptions:usingBlock:

Executes a given block using each object in the array with the specified options.

enumerateObjectsAtIndexes:options:usingBlock:

Executes a given block using the objects in the array at the specified indexes.

Comparing Arrays

firstObjectCommonWithArray:

Returns the first object contained in the receiving array that’s equal to an object in another given array.

isEqualToArray:

Compares the receiving array to another array.

Deriving New Arrays

arrayByAddingObject:

Returns a new array that is a copy of the receiving array with a given object added to the end.

arrayByAddingObjectsFromArray:

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

filteredArrayUsingPredicate:

Evaluates a given predicate against each object in the receiving array and returns a new array containing the objects for which the predicate returns true.

subarrayWithRange:

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

Sorting

sortedArrayHint

Analyzes the array and returns a “hint” that speeds the sorting of the array when the hint is supplied to sortedArrayUsingFunction:context:hint:.

sortedArrayUsingFunction:context:

Returns a new array that lists the receiving array’s elements in ascending order as defined by the comparison function comparator.

sortedArrayUsingFunction:context:hint:

Returns a new array that lists the receiving array’s elements in ascending order as defined by the comparison function comparator.

sortedArrayUsingDescriptors:

Returns a copy of the receiving array sorted as specified by a given array of sort descriptors.

sortedArrayUsingSelector:

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

sortedArrayUsingComparator:

Returns an array that lists the receiving array’s elements in ascending order, as determined by the comparison method specified by a given NSComparator block.

sortedArrayWithOptions:usingComparator:

Returns an array that lists the receiving array’s elements in ascending order, as determined by the comparison method specified by a given NSComparator block.

NSComparator

Defines the signature for a block object used for comparison operations.

Working with String Elements

componentsJoinedByString:

Constructs and returns an NSString object that is the result of interposing a given separator between the elements of the array.

Creating a Description

description

A string that represents the contents of the array, formatted as a property list.

descriptionWithLocale:

Returns a string that represents the contents of the array, formatted as a property list.

descriptionWithLocale:indent:

Returns a string that represents the contents of the array, formatted as a property list.

Storing Arrays

writeToFile:atomically:

Writes the contents of the array to a file at a given path.

Deprecated
writeToURL:atomically:

Writes the contents of the array to the location specified by a given URL.

Deprecated

Collecting Paths

pathsMatchingExtensions:

Returns an array containing all the pathname elements in the receiving array that have filename extensions from a given array.

Key-Value Observing

removeObserver:forKeyPath:

Raises an exception.

addObserver:toObjectsAtIndexes:forKeyPath:options:context:

Registers an observer to receive key value observer notifications for the specified key-path relative to the objects at the indexes.

removeObserver:fromObjectsAtIndexes:forKeyPath:

Removes anObserver from all key value observer notifications associated with the specified keyPath relative to the array’s objects at indexes.

Key-Value Coding

setValue:forKey:

Invokes setValue:forKey: on each of the array's items using the specified value and key.

valueForKey:

Returns an array containing the results of invoking valueForKey: using key on each of the array's objects.

Randomly Shuffling an Array

shuffledArray

Returns a new array that lists this array’s elements in a random order.

shuffledArrayWithRandomSource:

Returns a new array that lists this array’s elements in a random order, using the specified random source.

Constants

Instance Methods

See Also

Basic Collections

NSMutableArray

A dynamic ordered collection of objects.

NSDictionary

A static collection of objects associated with unique keys.

NSMutableDictionary

A dynamic collection of objects associated with unique keys.

NSSet

A static unordered collection of unique objects.

NSMutableSet

A dynamic unordered collection of unique objects.