Instance Method

sortedArrayUsingFunction:context:

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

Declaration

- (NSArray<ObjectType> *)sortedArrayUsingFunction:(NSInteger (*)(ObjectType, ObjectType, void *))comparator context:(void *)context;

Discussion

The new array contains references to the receiving array’s elements, not copies of them.

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:

NSInteger 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

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

Beta Software

This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.

Learn more about using Apple's beta software