PATH  Documentation > Mac OS X > Foundation Reference: Objective-C



Table of Contents

NSArray


Inherits from:
NSObject
Conforms to:
NSCoding
NSCopying
NSMutableCopying
NSObject (NSObject)
Declared in:
Foundation/NSArray.h



Class at a Glance


An NSArray stores an immutable array of objects.

Principal Attributes


Creation



+ array Returns an empty array.
+ arrayWithArray: Returns an array containing the elements from another array.
+ arrayWithContentsOfFile: Returns an array initialized from the contents of a file.
+ arrayWithObject: Returns an array containing a single object.
+ arrayWithObjects: Returns an array containing multiple objects.
+ arrayWithObjects:count: Returns an array containing a specified number of objects.

Commonly Used Methods



- count Returns the number of objects currently in the array.
- objectAtIndex: Returns the object located at the specified index.


Class Description


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

NSArray and NSMutableArray are part of a class cluster, so arrays are not actual instances of the NSArray or NSMutableArray classes but of one of their private subclasses. Although an array's class is private, its interface is public, as declared by these abstract superclasses, NSArray and NSMutableArray.

Generally, you instantiate an array by sending one of the array... messages to either the NSArray or NSMutableArray class object. These methods return an array containing the elements you pass in as arguments. (Note that arrays can't contain nil.) In general, objects that you add to an array aren't copied; rather, each object receives a retain message before its id is added to the array. When an object is removed from an array, it's sent a release message.

The NSArray and NSMutableArray classes adopt the NSCopying and NSMutableCopying protocols, making it convenient to convert an array of one type to the other.

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, such as 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. indexOfObject: 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 isEqual: message, as declared in the NSObject protocol. Another method, indexOfObjectIdenticalTo:, is provided for the less common case of determining whether a specific object is present in the array. indexOfObjectIdenticalTo: tests each element in the array to see whether its id matches that of the argument.

NSArray's makeObjectsPerformSelector: and makeObjectsPerformSelector:withObject:methods let you send messages to all objects in the array. To act on the array as a whole, a variety of other methods are defined. You can create a sorted version of the array ( sortedArrayUsingSelector: and sortedArrayUsingFunction:context:), extract a subset of the array ( subarrayWithRange:), or concatenate the elements of an array of NSStrings 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:.




Adopted Protocols


NSCoding
- encodeWithCoder:
- initWithCoder:
NSCopying
- copyWithZone:
NSMutableCopying
- mutableCopyWithZone:


Method Types


Creating an array
+ array
+ arrayWithArray:
+ arrayWithContentsOfFile:
+ arrayWithObject:
+ arrayWithObjects:
+ arrayWithObjects:count:
- initWithArray:
- initWithContentsOfFile:
- initWithContentsOfURL:
- initWithObjects:
- initWithObjects:count:
Querying the array
- containsObject:
- count
- getObjects:
- getObjects:range:
- indexOfObject:
- indexOfObject:inRange:
- indexOfObjectIdenticalTo:
- indexOfObjectIdenticalTo:inRange:
- lastObject
- objectAtIndex:
- objectEnumerator
- reverseObjectEnumerator
Sending messages to elements
- makeObjectsPerformSelector:
- makeObjectsPerformSelector:withObject:
Comparing arrays
- firstObjectCommonWithArray:
- isEqualToArray:
Deriving new arrays
- arrayByAddingObject:
- arrayByAddingObjectsFromArray:
- sortedArrayHint
- sortedArrayUsingFunction:context:
- sortedArrayUsingFunction:context:hint:
- sortedArrayUsingSelector:
- subarrayWithRange:
Working with string elements
- componentsJoinedByString:
- pathsMatchingExtensions:
Creating a description of the array
- description
- descriptionWithLocale:
- descriptionWithLocale:indent:
- writeToFile:atomically:
- writeToURL:atomically:
Working with array elements
- exchangeObjectAtIndex:withObjectAtIndex:


Class Methods



array

+ (id)array

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

See Also: + arrayWithObject:, + arrayWithObjects:



arrayWithArray:

+ (id)arrayWithArray:(NSArray *)anArray

Creates and returns an array containing the objects in anArray.

See Also: + arrayWithObjects:, - initWithObjects:



arrayWithContentsOfFile:

+ (id)arrayWithContentsOfFile:(NSString *)aPath

Creates and returns an array containing the contents of the file specified by aPath. The file identified by aPath must contain a string representation produced by the writeToFile:atomically: method. In addition, the array representation must contain only property list objects (NSString, NSData, NSArray, or NSDictionary objects).

Returns nil if the file can't be opened or if the contents of the file can't be parsed into an array.

See Also: - writeToFile:atomically:



arrayWithContentsOfURL:

+ (id)arrayWithContentsOfURL:(NSURL *)anURL

Creates and returns an array containing the contents specified by anURL. The location identified by anURL must contain a string representation produced by the writeToURL:atomically: method. In addition, the array representation must contain only property list objects (NSString, NSData, NSArray, or NSDictionary objects).

Returns nil if the location can't be opened or if the contents of the location can't be parsed into an array.

See Also: - writeToURL:atomically:



arrayWithObject:

+ (id)arrayWithObject:(id)anObject

Creates and returns an array containing the single element anObject.

See Also: + array, + arrayWithObjects:



arrayWithObjects:

+ (id)arrayWithObjects:(id)firstObj, ...

Creates and returns an array containing the objects in the argument list. The argument list is a comma-separated list of objects ending with nil.

This code example creates an array containing three different types of elements (assuming aPath exists):

NSArray *myArray;
NSData *someData = [NSData dataWithContentsOfFile:aPath]; 
NSValue *aValue = [NSNumber numberWithInt:5]; 
NSString *aString = @"a string";
	
myArray = [NSArray arrayWithObjects:someData, aValue, 
    aString, nil];

See Also: + array, + arrayWithObject:



arrayWithObjects:count:

+ (id)arrayWithObjects:(id *)objects count:(unsigned)count

Creates and returns an array containing count objects from objects.

See Also: - getObjects:, - getObjects:range:




Instance Methods



arrayByAddingObject:

- (NSArray *)arrayByAddingObject:(id)anObject

Returns a new array that is a copy of the receiver with anObject added to the end. Because anObject is added to the array, it receives a retain message. If anObject is nil, an NSInvalidArgumentException is raised.

See Also: - addObject: (NSMutableArray)



arrayByAddingObjectsFromArray:

- (NSArray *)arrayByAddingObjectsFromArray:(NSArray *)otherArray

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

See Also: - addObjectsFromArray: (NSMutableArray)



componentsJoinedByString:

- (NSString *)componentsJoinedByString:(NSString *)separator

Constructs and returns an NSString that is the result of interposing separator between the elements of the receiver's array. For example, this code excerpt writes the path System/Developer to the console:
NSArray *pathArray = [NSArray arrayWithObjects:@"System",
    @"Developer", nil];
NSLog("The path is /%@.\n", 
    [pathArray componentsJoinedByString:@"/"]);

Each element in the receiver's array must handle description. If the receiver has no elements, an NSString representing an empty string is returned.

See Also: - componentsSeparatedByString: (NSString)



containsObject:

- (BOOL)containsObject:(id)anObject

Returns YES if anObject is present in the array. This method determines whether an object is present in the array by sending an isEqual: message to each of the array's objects (and passing anObject as the parameter to each isEqual: message).

See Also: - indexOfObject:, - indexOfObjectIdenticalTo:, isEqual: (NSObject protocol)



count

- (unsigned)count

Returns the number of objects currently in the array.

See Also: - objectAtIndex:



description

- (NSString *)description

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

See Also: - descriptionWithLocale:, - descriptionWithLocale:indent:



descriptionWithLocale:

- (NSString *)descriptionWithLocale:(NSDictionary *)locale

Returns a string that represents the contents of the receiver, formatted as a property list. locale specifies options used for formatting each of the receiver's elements (where recognized); specify nil if you don't want the elements formatted.

For a description of how locale is applied to each element in the receiving array, see descriptionWithLocale:indent:.

See Also: - description, - descriptionWithLocale:indent:



descriptionWithLocale:indent:

- (NSString *)descriptionWithLocale:(NSDictionary *)locale indent:(unsigned)level

Returns a string that represents the contents of the receiver, formatted as a property list. locale specifies options used for formatting each of the receiver's elements; specify nil if you don't want the elements formatted. level allows you to specify a level of indent, to make the output more readable: set level to 0 to use four spaces to indent, or 1 to indent the output with a tab character.

The returned NSString contains the string representations of each of the receiver's elements, in order, from first to last. To obtain the string representation of a given element, descriptionWithLocale:indent: proceeds as follows:

See Also: - description, - descriptionWithLocale:



exchangeObjectAtIndex:withObjectAtIndex:

- (void)exchangeObjectAtIndex:(unsigned)idx1 withObjectAtIndex:(unsigned)idx2

Description forthcoming.

firstObjectCommonWithArray:

- (id)firstObjectCommonWithArray:(NSArray *)otherArray

Returns the first object contained in the receiver that's equal to an object in otherArray. If no such object is found, this method returns nil. This method uses isEqual: to check for object equality.

See Also: - containsObject:, isEqual: (NSObject protocol)



getObjects:

- (void)getObjects:(id *)aBuffer

Copies all the objects contained in the receiver to aBuffer.

See Also: + arrayWithObjects:count:



getObjects:range:

- (void)getObjects:(id *)aBuffer range:(NSRange)aRange

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

See Also: + arrayWithObjects:count:



indexOfObject:

- (unsigned)indexOfObject:(id)anObject

Searches the receiver for anObject and returns the lowest index whose corresponding array value is equal to anObject. Objects are considered equal if isEqual: returns YES. If none of the objects in the receiver are equal to anObject, indexOfObject: returns NSNotFound.

See Also: - containsObject:, - indexOfObjectIdenticalTo:, isEqual: (NSObject protocol)



indexOfObject:inRange:

- (unsigned)indexOfObject:(id)anObject inRange:(NSRange)range

Searches the specified range within the receiver for anObject and returns the lowest index whose corresponding array value is equal to anObject. Objects are considered equal if isEqual: returns YES. If none of the objects in the specified range are equal to anObject, indexOfObject:inRange: returns NSNotFound.

See Also: - containsObject:, - indexOfObjectIdenticalTo:inRange:, isEqual: (NSObject protocol)



indexOfObjectIdenticalTo:

- (unsigned)indexOfObjectIdenticalTo:(id)anObject

Searches the receiver for anObject (testing for equality by comparing object addresses) and returns the lowest index whose corresponding array value is identical to anObject. If none of the objects in the receiver are identical to anObject, indexOfObjectIdenticalTo: returns NSNotFound.

See Also: - containsObject:, - indexOfObject:



indexOfObjectIdenticalTo:inRange:

- (unsigned)indexOfObjectIdenticalTo:(id)anObject inRange:(NSRange)range

Searches the specified range within the receiver for anObject (testing for equality by comparing object addresses) and returns the lowest index whose corresponding array value is identical to anObject. If none of the objects in the specified range are identical to anObject, indexOfObjectIdenticalTo:inRange: returns NSNotFound.

See Also: - containsObject:, - indexOfObject:inRange:



initWithArray:

- (id)initWithArray:(NSArray *)anArray

Initializes a newly allocated array by placing in it the objects contained in anArray. Each object in anArray receives a retain message as it's added to the array. After an immutable array has been initialized in this way, it can't be modified. Returns self.

See Also: + arrayWithObject:, - initWithObjects:



initWithContentsOfFile:

- (id)initWithContentsOfFile:(NSString *)aPath

Initializes a newly allocated array with the contents of the file specified by aPath. The file identified by aPath must contain a string representation produced by the writeToFile:atomically: method. In addition, the array representation must contain only property list objects (NSString, NSData, NSArray, or NSDictionary objects).

Returns self if the receiver is successfully initialized, or nil if the file can't be opened or the contents of the file can't be parsed into an array.

See Also: + arrayWithContentsOfFile:, - writeToFile:atomically:



initWithContentsOfURL:

- (id)initWithContentsOfURL:(NSURL *)anURL

Initializes a newly allocated array with the contents of the location specified by anURL. The location identified by anURL must contain a string representation produced by the writeToURL:atomically: method. In addition, the array representation must contain only property list objects (NSString, NSData, NSArray, or NSDictionary objects).

Returns self if the receiver is successfully initialized, or nil if the file can't be opened or the contents of the file can't be parsed into an array.

See Also: + arrayWithContentsOfURL:, - writeToURL:atomically:



initWithObjects:

- (id)initWithObjects:(id)firstObj, ...

Initializes a newly allocated array by placing the objects in the argument list in it. This list is a comma-separated list of objects ending with nil. Objects are retained as they're added to the array. After an immutable array has been initialized in this way, it can't be modified. Returns self.

See Also: - initWithObjects:count:, + arrayWithObjects:, - initWithArray:



initWithObjects:count:

- (id)initWithObjects:(id *)objects count:(unsigned)count

Initializes a newly allocated array by placing count objects from the objects array in it. Each object in the objects array receives a retain message as it's added to the array. After an immutable array has been initialized in this way, it can't be modified. Returns self.

See Also: - initWithObjects:, + arrayWithObjects:, - initWithArray:



isEqualToArray:

- (BOOL)isEqualToArray:(NSArray *)otherArray

Compares the receiving array to otherArray. If the contents of otherArray are equal to the contents of the receiver, this method returns YES. If not, it returns NO.

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 isEqual: test.

See Also: isEqual: (NSObject protocol)



lastObject

- (id)lastObject

Returns the object in the array with the highest index value. If the array is empty, lastObject returns nil.

See Also: - removeLastObject (NSMutableArray)



makeObjectsPerformSelector:

- (void)makeObjectsPerformSelector:(SEL)aSelector

Sends the aSelector message to each object in the array, starting with the first object and continuing through the array to the last object. The aSelector method must take no arguments. It shouldn't have the side effect of modifying the receiving array. The messages are sent using the makeObjectsPerformSelector:withObject: method.

See Also: - makeObjectsPerformSelector:withObject:



makeObjectsPerformSelector:withObject:

- (void)makeObjectsPerformSelector:(SEL)aSelector withObject:(id)anObject

Sends the aSelector message to each object in the array, starting with the first object and continuing through the array to the last object. The message is sent each time with anObject as an argument, so the aSelector method must take a single argument of type id. The aSelector method shouldn't, as a side effect, modify the receiving array. The messages are sent using the performSelector:withObject: method declared in the NSObject protocol.

See Also: - makeObjectsPerformSelector:



objectAtIndex:

- (id)objectAtIndex:(unsigned)index

Returns the object located at index. If index is beyond the end of the array (that is, if index is greater than or equal to the value returned by count), an NSRangeException is raised.

See Also: - count



objectEnumerator

- (NSEnumerator *)objectEnumerator

Returns an enumerator object that lets you access each object in the array, in order, starting with the element at index 0, as in:
NSEnumerator *enumerator = [myArray objectEnumerator];
id anObject;
	
while ((anObject = [enumerator nextObject])) {
    /*  code to act on each element as it is returned */
}

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

See Also: - reverseObjectEnumerator, - nextObject (NSEnumerator)



pathsMatchingExtensions:

- (NSArray *)pathsMatchingExtensions:(NSArray *)filterTypes

Returns a new array that contains those string objects in the receiver that have a filename extension (as determined by NSString's pathExtension method) that matches one of the extensions in filterTypes. filterTypes should be an array of NSStrings, each of which identifies a filename extension to be matched (such as "tiff" or "eps"). Filenames that don't have an extension aren't included in the result. This method can be used to identify those files with a particular extension (or set of extensions) within a directory.

reverseObjectEnumerator

- (NSEnumerator *)reverseObjectEnumerator

Returns an enumerator object that lets you access each object in the array, in order, from the element at the highest index down to the element at index 0. Your code shouldn't modify the array during enumeration.

See Also: - objectEnumerator, - nextObject (NSEnumerator)



sortedArrayHint

- (NSData *)sortedArrayHint

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

sortedArrayUsingFunction:context:

- (NSArray *)sortedArrayUsingFunction:(int (*)(id, id, void *))comparator context:(void *)context

Returns a new array that lists the receiver's elements in ascending order as defined by the comparison function comparator. 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 comparison function is used to compare two elements at a time and should return NSOrderedAscending if the first element is smaller than the second, NSOrderedDescending if the first element is larger than the second, and NSOrderedSame if the elements are equal. Each time the comparison function is called, it's passed context as its third argument. This allows the comparison to be based on some outside parameter, such as whether character sorting is case-sensitive or case-insensitive.

Given anArray (an array of NSNumber objects) and a comparison function of this type:

int intSort(id num1, id num2, void *context)
{
    int v1 = [num1 intValue];
    int v2 = [num2 intValue];
    if (v1 < v2)
        return NSOrderedAscending;
    else if (v1 > v2)
        return NSOrderedDescending;
    else
        return NSOrderedSame;
}

A sorted version of anArray is created in this way:

NSArray *sortedArray; sortedArray = [anArray sortedArrayUsingFunction:intSort context:NULL];

See Also: - sortedArrayUsingSelector:



sortedArrayUsingFunction:context:hint:

- (NSArray *)sortedArrayUsingFunction:(int (*)(id, id, void *))comparator context:(void *)context hint:(NSData *)hint

Similar to sortedArrayUsingFunction:context:, except that it uses the supplied hint to speed the sorting process. To obtain an appropriate hint, use sortedArrayHint. When you know the array is nearly sorted, this method is faster than sortedArrayUsingFunction:context:.

sortedArrayUsingSelector:

- (NSArray *)sortedArrayUsingSelector:(SEL)comparator

Returns an array that lists the receiver's elements in ascending order, as determined by the comparison method specified by the selector comparator. 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 comparator message is sent to each object in the array, and has as its single argument another object in the array. The comparator method is used to compare two elements at a time and should return NSOrderedAscending if the receiver is smaller than the argument, NSOrderedDescending if the receiver is larger than the argument, and NSOrderedSame if they are equal.

For example, an array of NSStrings can be sorted by using the compare: method declared in the NSString class. Assuming anArray exists, a sorted version of the array can be created in this way:

NSArray *sortedArray = 
    [anArray sortedArrayUsingSelector:@selector(compare:)];

See Also: - sortedArrayUsingFunction:context:



subarrayWithRange:

- (NSArray *)subarrayWithRange:(NSRange)range

Returns a new array containing the receiver's elements that fall within the limits specified by range. If range isn't within the receiver's range of elements, an NSRangeException is raised. Each object receives a retain message as it's added to the array.

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

NSArray *halfArray;
NSRange theRange;
	
theRange.location = 0;
theRange.length = [wholeArray count] / 2;
	
halfArray = [wholeArray subarrayWithRange:theRange];



writeToFile:atomically:

- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag

Writes the contents of the receiver to the file specified by path. If the receiver's contents are all property list objects (NSString, NSData, NSArray, or NSDictionary objects), the file written by this method can be used to initialize a new array with the class method arrayWithContentsOfFile:or the instance method initWithContentsOfFile:.

If flag is YES, the array is written to an auxiliary file, and then the auxiliary file is renamed to path. If flag is NO, the array is written directly to path. The YES option guarantees that path, if it exists at all, won't be corrupted even if the system should crash during writing.

If path contains a tilde (~) character, you must expand it with stringByExpandingTildeInPath before invoking this method.

This method returns YES if the file is written successfully, and NO otherwise.

See Also: - initWithContentsOfFile:



writeToURL:atomically:

- (BOOL)writeToURL:(NSURL *)anURL atomically:(BOOL)atomically

Writes the contents of the receiver to the location specified by anURL. If the receiver's contents are all property list objects (NSString, NSData, NSArray, or NSDictionary objects), the location written by this method can be used to initialize a new array with the class method arrayWithContentsOfURL:or the instance method initWithContentsOfURL:.

If flag is YES, the array is written to an auxiliary location, and then the auxiliary location is renamed to anURL. If flag is NO, the array is written directly to anURL. The YES option guarantees that anURL, if it exists at all, won't be corrupted even if the system should crash during writing.

This method returns YES if the location is written successfully, and NO otherwise.

See Also: - initWithContentsOfURL:




Table of Contents