NSMutableArray Class Reference

Inherits from
Conforms to
Framework
/System/Library/Frameworks/Foundation.framework
Availability
Available in iOS 2.0 and later.
Declared in
NSArray.h
NSPredicate.h
NSSortDescriptor.h
Companion guides
Related sample code

Overview

The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray.

NSMutableArray is “toll-free bridged” with its Core Foundation counterpart, CFMutableArrayRef. See “Toll-Free Bridging” for more information.

Subclassing Notes

There is typically little reason to subclass NSMutableArray. The class does well what it is designed to do—maintain a mutable, 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

NSMutableArray defines five primitive methods:

In a subclass, you must override all these methods. You must also override the primitive methods of the NSArray class.

Tasks

Creating and Initializing a Mutable Array

Adding Objects

Removing Objects

Replacing Objects

Filtering Content

Rearranging Content

Class Methods

arrayWithCapacity:

Creates and returns an NSMutableArray object with enough allocated memory to initially hold a given number of objects.

+ (instancetype)arrayWithCapacity:(NSUInteger)numItems
Parameters
numItems

The initial capacity of the new array.

Return Value

A new NSMutableArray object with enough allocated memory to hold numItems objects.

Discussion

Mutable arrays expand as needed; numItems simply establishes the object’s initial capacity.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSArray.h

Instance Methods

addObject:

Inserts a given object at the end of the array.

- (void)addObject:(id)anObject
Parameters
anObject

The object to add to the end of the array's content. This value must not be nil.

Important: Raises an NSInvalidArgumentException if anObject is nil.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSArray.h

addObjectsFromArray:

Adds the objects contained in another given array to the end of the receiving array’s content.

- (void)addObjectsFromArray:(NSArray *)otherArray
Parameters
otherArray

An array of objects to add to the end of the receiving array’s content.

Availability
  • Available in iOS 2.0 and later.
Related Sample Code
Declared In
NSArray.h

exchangeObjectAtIndex:withObjectAtIndex:

Exchanges the objects in the array at given indices.

- (void)exchangeObjectAtIndex:(NSUInteger)idx1 withObjectAtIndex:(NSUInteger)idx2
Parameters
idx1

The index of the object with which to replace the object at index idx2.

idx2

The index of the object with which to replace the object at index idx1.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSArray.h

filterUsingPredicate:

Evaluates a given predicate against the array’s content and leaves only objects that match

- (void)filterUsingPredicate:(NSPredicate *)predicate
Parameters
predicate

The predicate to evaluate against the array's elements.

Availability
  • Available in iOS 3.0 and later.
See Also
Declared In
NSPredicate.h

init

Initializes a newly allocated array.

- (instancetype)init
Return Value

An array.

Discussion

This method is a designated initializer.

Availability
  • Available in iOS 7.0 and later.
Declared In
NSArray.h

initWithCapacity:

Returns an array, initialized with enough memory to initially hold a given number of objects.

- (instancetype)initWithCapacity:(NSUInteger)numItems
Parameters
numItems

The initial capacity of the new array.

Return Value

An array initialized with enough memory to hold numItems objects. The returned object might be different than the original receiver.

Discussion

Mutable arrays expand as needed; numItems simply establishes the object’s initial capacity.

This method is a designated initializer.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSArray.h

insertObject:atIndex:

Inserts a given object into the array's contents at a given index.

- (void)insertObject:(id)anObject atIndex:(NSUInteger)index
Parameters
anObject

The object to add to the array's content. This value must not be nil.

Important: Raises an NSInvalidArgumentException if anObject is nil.

index

The index in the array at which to insert anObject. This value must not be greater than the count of elements in the array.

Important: Raises an NSRangeException if index is greater than the number of elements in the array.

Discussion

If index is already occupied, the objects at index and beyond are shifted by adding 1 to their indices to make room.

Note that NSArray objects are not like C arrays. That is, even though you specify a size when you create an array, the specified size is regarded as a “hint”; the actual size of the array is still 0. This means that you cannot insert an object at an index greater than the current count of an array. For example, if an array contains two objects, its size is 2, so you can add objects at indices 0, 1, or 2. Index 3 is illegal and out of bounds; if you try to add an object at index 3 (when the size of the array is 2), NSMutableArray raises an exception.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSArray.h

insertObjects:atIndexes:

Inserts the objects in the provided array into the receiving array at the specified indexes.

- (void)insertObjects:(NSArray *)objects atIndexes:(NSIndexSet *)indexes
Parameters
objects

An array of objects to insert into the receiving array.

indexes

The indexes at which the objects in objects should be inserted. The count of locations in indexes must equal the count of objects. For more details, see the Discussion.

Discussion

Each object in objects is inserted into the receiving array in turn at the corresponding location specified in indexes after earlier insertions have been made. The implementation is conceptually similar to that illustrated in the following example.

- void insertObjects:(NSArray *)additions atIndexes:(NSIndexSet *)indexes
{
    NSUInteger currentIndex = [indexes firstIndex];
    NSUInteger i, count = [indexes count];
 
    for (i = 0; i < count; i++)
    {
        [self insertObject:[additions objectAtIndex:i] atIndex:currentIndex];
        currentIndex = [indexes indexGreaterThanIndex:currentIndex];
    }
}

The resulting behavior is illustrated by the following example.

NSMutableArray *array = [NSMutableArray arrayWithObjects: @"one", @"two", @"three", @"four", nil];
NSArray *newAdditions = [NSArray arrayWithObjects: @"a", @"b", nil];
NSMutableIndexSet *indexes = [NSMutableIndexSet indexSetWithIndex:1];
[indexes addIndex:3];
[array insertObjects:newAdditions atIndexes:indexes];
NSLog(@"array: %@", array);
 
// Output: array: (one, a, two, b, three, four)

The locations specified by indexes may therefore only exceed the bounds of the receiving array if one location specifies the count of the array or the count of the array after preceding insertions, and other locations exceeding the bounds do so in a contiguous fashion from that location, as illustrated in the following examples.

In this example, both new objects are appended to the end of the array.

NSMutableArray *array = [NSMutableArray arrayWithObjects: @"one", @"two", @"three", @"four", nil];
NSArray *newAdditions = [NSArray arrayWithObjects: @"a", @"b", nil];
NSMutableIndexSet *indexes = [NSMutableIndexSet indexSetWithIndex:5];
[indexes addIndex:4];
[array insertObjects:newAdditions atIndexes:indexes];
NSLog(@"array: %@", array);
 
// Output: array: (one, two, three, four, a, b)

If you replace [indexes addIndex:4] with [indexes addIndex:6] (so that the indexes are 5 and 6), then the application will fail with an out of bounds exception.

In this example, two objects are added into the middle of the array, and another at the current end of the array (index 4) which means that it is third from the end of the modified array.

NSMutableArray *array = [NSMutableArray arrayWithObjects: @"one", @"two", @"three", @"four", nil];
NSArray *newAdditions = [NSArray arrayWithObjects: @"a", @"b", @"c", nil];
NSMutableIndexSet *indexes = [NSMutableIndexSet indexSetWithIndex:1];
[indexes addIndex:2];
[indexes addIndex:4];
[array insertObjects:newAdditions atIndexes:indexes];
NSLog(@"array: %@", array);
 
// Output: array: (one, a, b, two, c, three, four)

If you replace [indexes addIndex:4] with [indexes addIndex:6] (so that the indexes are 1, 2, and 6), then the output is (one, a, b, two, three, four, c).

If objects or indexes is nil this method will raise an exception.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSArray.h

removeAllObjects

Empties the array of all its elements.

- (void)removeAllObjects
Availability
  • Available in iOS 2.0 and later.
Related Sample Code
Declared In
NSArray.h

removeLastObject

Removes the object with the highest-valued index in the array

- (void)removeLastObject
Discussion

removeLastObject raises an NSRangeException if there are no objects in the array.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSArray.h

removeObject:

Removes all occurrences in the array of a given object.

- (void)removeObject:(id)anObject
Parameters
anObject

The object to remove from the array.

Discussion

This method uses indexOfObject: to locate matches and then removes them by using removeObjectAtIndex:. Thus, matches are determined on the basis of an object’s response to the isEqual: message. If the array does not contain anObject, the method has no effect (although it does incur the overhead of searching the contents).

Availability
  • Available in iOS 2.0 and later.
Declared In
NSArray.h

removeObject:inRange:

Removes all occurrences within a specified range in the array of a given object.

- (void)removeObject:(id)anObject inRange:(NSRange)aRange
Parameters
anObject

The object to remove from the array's content.

aRange

The range from which to remove anObject.

Important: Raises an NSRangeException if aRange exceeds the bounds of the array.

Discussion

Matches are determined on the basis of an object’s response to the isEqual: message. If the array does not contain anObject within aRange, the method has no effect (although it does incur the overhead of searching the contents).

Availability
  • Available in iOS 2.0 and later.
Declared In
NSArray.h

removeObjectAtIndex:

Removes the object at index .

- (void)removeObjectAtIndex:(NSUInteger)index
Parameters
index

The index from which to remove the object in the array. The value must not exceed the bounds of the array.

Important: Raises an NSRangeException if index is beyond the end of the array.

Discussion

To fill the gap, all elements beyond index are moved by subtracting 1 from their index.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSArray.h

removeObjectIdenticalTo:

Removes all occurrences of a given object in the array.

- (void)removeObjectIdenticalTo:(id)anObject
Parameters
anObject

The object to remove from the array.

Discussion

This method uses the indexOfObjectIdenticalTo: method to locate matches and then removes them by using removeObjectAtIndex:. Thus, matches are determined using object addresses. If the array does not contain anObject, the method has no effect (although it does incur the overhead of searching the contents).

Availability
  • Available in iOS 2.0 and later.
Declared In
NSArray.h

removeObjectIdenticalTo:inRange:

Removes all occurrences of anObject within the specified range in the array.

- (void)removeObjectIdenticalTo:(id)anObject inRange:(NSRange)aRange
Parameters
anObject

The object to remove from the array within aRange.

aRange

The range in the array from which to remove anObject.

Important: Raises an NSRangeException if aRange exceeds the bounds of the array.

Discussion

This method uses the indexOfObjectIdenticalTo: method to locate matches and then removes them by using removeObjectAtIndex:. Thus, matches are determined using object addresses. If the array does not contain anObject within aRange, the method has no effect (although it does incur the overhead of searching the contents).

Availability
  • Available in iOS 2.0 and later.
Declared In
NSArray.h

removeObjectsAtIndexes:

Removes the objects at the specified indexes from the array.

- (void)removeObjectsAtIndexes:(NSIndexSet *)indexes
Parameters
indexes

The indexes of the objects to remove from the array. The locations specified by indexes must lie within the bounds of the array.

Discussion

This method is similar to removeObjectAtIndex:, but allows you to efficiently remove multiple objects with a single operation. indexes specifies the locations of objects to be removed given the state of the array when the method is invoked, as illustrated in the following example.

NSMutableArray *array = [NSMutableArray arrayWithObjects: @"one", @"a", @"two", @"b", @"three", @"four", nil];
NSMutableIndexSet *indexes = [NSMutableIndexSet indexSetWithIndex:1];
[indexes addIndex:3];
[array removeObjectsAtIndexes:indexes];
NSLog(@"array: %@", array);
 
// Output: array: (one, two, three, four)

If indexes is nil this method will raise an exception.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSArray.h

removeObjectsInArray:

Removes from the receiving array the objects in another given array.

- (void)removeObjectsInArray:(NSArray *)otherArray
Parameters
otherArray

An array containing the objects to be removed from the receiving array.

Discussion

This method is similar to removeObject:, but allows you to efficiently remove large sets of objects with a single operation. If the receiving array does not contain objects in otherArray, the method has no effect (although it does incur the overhead of searching the contents).

This method assumes that all elements in otherArray respond to hash and isEqual:.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSArray.h

removeObjectsInRange:

Removes from the array each of the objects within a given range.

- (void)removeObjectsInRange:(NSRange)aRange
Parameters
aRange

The range of the objects to remove from the array.

Discussion

The objects are removed using removeObjectAtIndex:.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSArray.h

replaceObjectAtIndex:withObject:

Replaces the object at index with anObject.

- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject
Parameters
index

The index of the object to be replaced. This value must not exceed the bounds of the array.

Important: Raises an NSRangeException if index is beyond the end of the array.

anObject

The object with which to replace the object at index index in the array. This value must not be nil.

Important: Raises an NSInvalidArgumentException if anObject is nil.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSArray.h

replaceObjectsAtIndexes:withObjects:

Replaces the objects in the receiving array at specified locations specified with the objects from a given array.

- (void)replaceObjectsAtIndexes:(NSIndexSet *)indexes withObjects:(NSArray *)objects
Parameters
indexes

The indexes of the objects to be replaced.

objects

The objects with which to replace the objects in the receiving array at the indexes specified by indexes. The count of locations in indexes must equal the count of objects.

Discussion

The indexes in indexes are used in the same order as the objects in objects.

If objects or indexes is nil this method will raise an exception.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSArray.h

replaceObjectsInRange:withObjectsFromArray:

Replaces the objects in the receiving array specified by a given range with all of the objects from a given array.

- (void)replaceObjectsInRange:(NSRange)aRange withObjectsFromArray:(NSArray *)otherArray
Parameters
aRange

The range of objects to replace in (or remove from) the receiving array.

otherArray

The array of objects from which to select replacements for the objects in aRange.

Discussion

If otherArray has fewer objects than are specified by aRange, the extra objects in the receiving array are removed. If otherArray has more objects than are specified by aRange, the extra objects from otherArray are inserted into the receiving array.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSArray.h

replaceObjectsInRange:withObjectsFromArray:range:

Replaces the objects in the receiving array specified by one given range with the objects in another array specified by another range.

- (void)replaceObjectsInRange:(NSRange)aRange withObjectsFromArray:(NSArray *)otherArray range:(NSRange)otherRange
Parameters
aRange

The range of objects to replace in (or remove from) the receiving array.

otherArray

The array of objects from which to select replacements for the objects in aRange.

otherRange

The range of objects to select from otherArray as replacements for the objects in aRange.

Discussion

The lengths of aRange and otherRange don’t have to be equal: if aRange is longer than otherRange, the extra objects in the receiving array are removed; if otherRange is longer than aRange, the extra objects from otherArray are inserted into the receiving array.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSArray.h

setArray:

Sets the receiving array’s elements to those in another given array.

- (void)setArray:(NSArray *)otherArray
Parameters
otherArray

The array of objects with which to replace the receiving array's content.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSArray.h

setObject:atIndexedSubscript:

Replaces the object at the index with the new object, possibly adding the object.

- (void)setObject:(id)anObject atIndexedSubscript:(NSUInteger)index
Parameters
anObject

The object with which to replace the object at index index in the array. This value must not be nil.

Important: Raises an NSInvalidArgumentException if anObject is nil.

index

The index of the object to be replaced. This value must not exceed the bounds of the array.

Important: Raises an NSRangeException if index is beyond the end of the array.

Discussion

If the index is equal to count the element is added to the end of the array, growing the array.

Availability
  • Available in iOS 6.0 and later.
Declared In
NSArray.h

sortUsingComparator:

Sorts the array using the comparison method specified by a given NSComparator Block.

- (void)sortUsingComparator:(NSComparator)cmptr
Parameters
cmptr

A comparator block.

Availability
  • Available in iOS 4.0 and later.
Related Sample Code
Declared In
NSArray.h

sortUsingDescriptors:

Sorts the receiving array using a given array of sort descriptors.

- (void)sortUsingDescriptors:(NSArray *)sortDescriptors
Parameters
sortDescriptors

An array containing the NSSortDescriptor objects to use to sort the receiving array's contents.

Discussion

See NSSortDescriptor for additional information.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSSortDescriptor.h

sortUsingFunction:context:

Sorts the array’s elements in ascending order as defined by the comparison function compare.

- (void)sortUsingFunction:(NSInteger (*)(id, id, void *))compare context:(void *)context
Parameters
compare

The comparison function to use to compare two elements at a time.

The function's parameters are two objects to compare and the context parameter, context. The function 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.

context

The context argument to pass to the compare function.

Discussion

This approach allows the comparison to be based on some outside parameter, such as whether character sorting is case-sensitive or case-insensitive.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSArray.h

sortUsingSelector:

Sorts the array’s elements in ascending order, as determined by the comparison method specified by a given selector.

- (void)sortUsingSelector:(SEL)comparator
Parameters
comparator

A selector that specifies the comparison method to use to compare elements in the 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 should return NSOrderedAscending if the array is smaller than the argument, NSOrderedDescending if the array is larger than the argument, and NSOrderedSame if they are equal.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSArray.h

sortWithOptions:usingComparator:

Sorts the array using the specified options and the comparison method specified by a given NSComparator Block.

- (void)sortWithOptions:(NSSortOptions)opts usingComparator:(NSComparator)cmptr
Parameters
opts

A bitmask that specifies the options for the sort (whether it should be performed concurrently and whether it should be performed stably).

cmptr

A comparator block.

Availability
  • Available in iOS 4.0 and later.
Declared In
NSArray.h